Sunday, February 3, 2013

Send mail with Gmail SMTP and Xoauth (Xoauth.php)

Since I couldn't find a complete solution anywhere else, I thought I'd make a post about how to send mail using Gmail SMTP, Zend Mail and Xoauth2.

First, you need to put a file called Xoauth.php in Zend/Mail/Protocol/Smtp/Auth. The contents of the file are as follows:

require_once 'Zend/Mail/Protocol/Smtp.php';
class Zend_Mail_Protocol_Smtp_Auth_Xoauth extends Zend_Mail_Protocol_Smtp
 protected $_xoauth_request;
    public function __construct($host = '', $port = null, $config = null)
  if (isset($config['xoauth_request'])) {
   $this->_xoauth_request = $config['xoauth_request'];
     parent::__construct($host, $port, $config);
    public function auth()
  $this->_send('AUTH XOAUTH2 ' . $this->_xoauth_request);
  $this->_auth = true;

If you're curious about how this file gets called, look in Transport/Smtp.php for the _sendMail function. The variable connectionClass is what defines the file location.

Now to actually send the email you need the following code:
require_once 'Zend/Mail/Transport/Smtp.php';
require_once 'Zend/Mail.php';

function constructAuthString($email,$accessToken) {
  return base64_encode("user=$email\1auth=Bearer $accessToken\1\1");

function sendEmail($email,$accessToken){
 $smtpInitClientRequestEncoded = constructAuthString($email, $accessToken);
 $config = array('ssl' => 'ssl',
                  'port' => '465',
                  'auth' => 'xoauth',
                  'xoauth_request' => $smtpInitClientRequestEncoded);
 $transport = new Zend_Mail_Transport_Smtp('', $config); 
 $mail = new Zend_Mail();
 $mail->setBodyText('some body text');
 $mail->setFrom($email, 'Some Sender');
 $mail->addTo("email of recipient", 'Some Recipient');
 $mail->setSubject('Test sending by smtp');

Call sendEmail() with the arguments email and accessToken and you'll be sending an email with Gmail SMTP and XOauth!

Note: I'll put this stuff on Github in a bit.