Thursday, July 26, 2012

Send Email Using CakePhp 2.0.6 and CakeEmail

Edit app/Config/email.php
public $default = array(
        'transport' => 'Smtp',
        'host' => '',
        'port' => 25,
        'timeout' => 300,
        'username' => '',
        'password' => '',
        'charset' => 'utf-8',
        'headerCharset' => 'utf-8',
    );

Create a component in app/Controller/Component as EmailHandlerServiceComponent.php
<?php
    class EmailHandlerServiceComponent extends Object {
        var $controller;

        public function sendEmail($to = "", $from = "", $fromName = "", $subject = "No Subject", $values = array())
        {
            App::uses('CakeEmail', 'Network/Email');
            $emailSender = new CakeEmail('default');
            $emailSender->to($to);
            $emailSender->subject(utf8Encode($subject));
            $emailSender->from(array($from=>$fromName));
            $emailSender->emailFormat('both');
            $emailSender->viewVars($values);
            $emailSender->template("first", "default");
            if ($emailSender->send()) {
                return true;
            } else {
                return false;
            }
        }
    }
?>

Create a file app/View/Layouts/Emails/html/default.php
Create a file app/View/Layouts/Emails/text/default.php 

Create a file app/View/Emails/html/first.php  
Create a file app/View/Emails/text/first.php 

Call sendEmail() from any controller.

You May Need To Edit app/lib/Cake/Network/Email/CakeEmail.php to set $this->charset and $this->_appCharset, set them to "utf-8" as default. 

No comments:

Post a Comment