CakePHP: PHPMailer Component – Using GMail SMTP

Requirements:

  1. CakePHP 2.x
  2. PHPMailer

Download PHPMailer & extract it to APP/vendors.

Add following lines in APP/vendors/phpmailer/class.phpmail.php line 542, in ELSE statement. This to ensure we have a secured domain through SSL / TLS.

// add a variable named SMTPSecure - SSL / TLS
var $SMTPSecure

// line 542 
if(!empty($this->SMTPSecure))
{
    $secure = $this->SMTPSecure . '://';
}

Create a component called EmailComponent in APP/app/Controller/Component

<?php

App::uses('Component', 'Controller');
App::import('Vendor', 'phpmailer', array('file' => 'phpmailer'.DS.'class.phpmailer.php'));

class EmailComponent extends Component {

  public function send($to, $subject, $message) {
    $sender = "from_you@you.com"; // this will be overwritten by GMail

    $header = "X-Mailer: PHP/".phpversion() . "Return-Path: $sender";

    $mail = new PHPMailer();

    $mail->IsSMTP();
    $mail->Host = "smtp.gmail.com"; 
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = "ssl";
    $mail->Port = 465;
    $mail->SMTPDebug  = 2; // turn it off in production
    $mail->Username   = "[yourGMailAccount]@gmail.com";  
    $mail->Password   = "password";
    
    $mail->From = $sender;
    $mail->FromName = "From Me";

    $mail->AddAddress($to);

    $mail->IsHTML(true);
    $mail->CreateHeader($header);

    $mail->Subject = $subject;
    $mail->Body    = nl2br($message);
    $mail->AltBody = nl2br($message);

    // return an array with two keys: error & message
    if(!$mail->Send()) {
      return array('error' => true, 'message' => 'Mailer Error: ' . $mail->ErrorInfo);
    } else {
      return array('error' => false, 'message' =>  "Message sent!");
    }
  }
}

?>

Create a controller, ExampleController.php to test out our EmailComponent

<?php

App::uses('AppController', 'Controller');

class ExampleController extends AppController {
	public $components = array('Email');
	public function index() {
		// just to test out the sending email using SMTP is OK, create a method that will be able to access from public
		$to = '[someone@you.com]';
		$subject = 'Hi buddy, i got a message for you.';
		$message = 'Nothing much. Just test out my Email Component using PHPMailer.'
		$mail = $this->Email->send($to, $subject, $message);
		$this->set('mail',$mail);
		$this->render(false);
	}
}

When you navigate to http://localhost/APP/Example, the email should send to [someone@you.com]. Please do check the mailbox. 🙂

References:

  1. http://phpmailer.worxware.com/?pg=examplebgmail
  2. http://blog.teamtreehouse.com/sending-email-with-phpmailer-and-smtp
  3. http://book.cakephp.org/2.0/en/controllers/components.html#creating-a-component

Leave a comment