CakePHP Gmail Component
Here is a very simple but useful component for easily sending emails from a Gmail account in CakePHP.
Note: Google imposes a limit of 500 outgoing messages per day for Gmail accounts. If you go past that, your account will be locked out for 24 hours (possibly longer). So don't count on GMail for sending bulk email of any kind.
Installation
Copy the code below and save it in app/controllers/components/gmail.php
App::import('Component', 'Email');
class GmailComponent extends EmailComponent {
function initialize(&$controller) {
$this->controller =& $controller;
}
function send() {
$this->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'host' => 'ssl://smtp.gmail.com',
'username'=>$this->from['email'],
'password'=>$this->from['password']
);
$this->delivery = 'smtp';
$this->to = $this->to['name'] . ' <' . $this->to['email'] . '>';
$this->from = $this->from['name'] . ' <' . $this->from['email'] . '>';
if(parent::send()) {
return true;
}
$this->log($this->to);
$this->log($this->from);
$this->log($this->smtpError);
$this->log($this->smtpOptions);
return false;
}
}
Usage
Load the Gmail component in your controller:
var $components = array('Gmail');
Google expects the "To" and "From" parameters in an outgoing email to be formatted in this format:
Full Name <email@domain.com>. If you don't format it that way, Google will reject your message.
Instead of passing in a string for the "To" and "From" fields, you must pass in an array. This will ensure that the correct formatting is applied.
$this->Gmail->to = array(
'name' => 'Some Person',
'email' => 'some_person@domain.com'
);
$this->Gmail->subject = 'My Subject';
$this->Gmail->from = array(
'name' => 'My Name',
'email' => 'my_email@gmail.com',
'password' => 'my_password'
);
$this->Gmail->template = 'my_template';
$this->Gmail->sendAs = 'both';
if(!$this->Gmail->send()) {
// Handle send failure
}
Comments (0)
Leave a comment