Friday, August 5, 2011

Sending Email

Sending email in CakePHP is quite simple, however, it can be simpler, especially if you want to follow the DRY methodology. In the controller you want to send email from simply add the following function:
    function __sendEmail($to, $subject, $data, $template, $cc = false){
        $this->Email->reset();
        $this->Email->from = 'Your Name Here<your@email.here>';
        $this->Email->replyTo = 'your@email.here';
        $this->Email->additionalParams = '-fyour@email.here';
        $this->Email->sendAs = 'both';
        $this->Email->template = $template;
        $this->Email->subject = $subject;
        $this->Email->to = $to;
        if($cc) $this->Email->cc = array($cc);
        $this->set('data', $data);
        if ($this->Email->send()) {
            return true;
        } else {
            return false;
        }    
    }
Now you can call it with a single line:
$this->__sendEmail('to@email.here', 'Subject', $data, 'templateName', 'cc@email.here'));

No comments:

Post a Comment