Skip to content

Instantly share code, notes, and snippets.

@pykotechguy
Created July 18, 2014 10:01
Show Gist options
  • Save pykotechguy/ccaa46ba95b10ac5f1e3 to your computer and use it in GitHub Desktop.
Save pykotechguy/ccaa46ba95b10ac5f1e3 to your computer and use it in GitHub Desktop.
CakePHP EmailerComponent SMTP
<?php
// /vendors/phpmailer/class.phpmail.php ->
// add a variable named SMTPSecure - SSL / TLS
var $SMTPSecure
// line 542
if(!empty($this->SMTPSecure))
{
$secure = $this->SMTPSecure . '://';
}
// http://nasrulhazim.wordpress.com/2014/04/12/cakephp-phpmailer-component-using-gmail-smtp/
//create `EmailComponent` in APP/app/Controller/Component
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 = "[email protected]"; // 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 = '[[email protected]]';
$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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment