Sending emails with Zend_Mail using Gmail or Google Apps

Zend Framework is currently one of the best MVC-based frameworks in the PHP world. Zend_Mail is part of Zend Framework and it provides the ability to easily send email messages. If you’re like me, most web applications you have developed are setup to use Google Apps as their email provider. Here’s how to send email messages via Gmail or Google Apps by using Zend_Mail.

public function send() {

 //Initialize needed variables
 $your_name = 'Mario Awad';
 $your_email = 'your_email@your_domain.com'; //Or your_email@gmail.com for Gmail
 $your_password = 'your_password';
 $send_to_name = 'My Friend';
 $send_to_email = 'myfriend@tempinbox.com';

 //SMTP server configuration
 $smtpHost = 'smtp.gmail.com';
 $smtpConf = array(
  'auth' => 'login',
  'ssl' => 'ssl',
  'port' => '465',
  'username' => $your_email,
  'password' => $your_password
 );
 $transport = new Zend_Mail_Transport_Smtp($smtpHost, $smtpConf);

 //Create email
 $mail = new Zend_Mail();
 $mail->setFrom($your_email, $your_name);
 $mail->addTo($send_to_email, $send_to_name);
 $mail->setSubject('Hello World');
 $mail->setBodyText('This is the body text of the email.');

 //Send
 $sent = true;
 try {
  $mail->send($transport);
 }
 catch (Exception $e) {
  $sent = false;
 }

 //Return boolean indicating success or failure
 return $sent;

}

In addition to the above code, please note the following:

  • You must enable the “php_openssl” extension to use the SSL transport protocol (Which is needed for Gmail and Google Apps). All you have to do is open your “php.ini” file and uncomment the line that includes the “php_openssl” extension (Search for “php_openssl” and you’ll find it).
  • I found many resources on the web stating that you should use the TLS transport protocol (They never mention how to use or setup the SSL transfer protocol). This didn’t work in my tests and always resulted in a timeout error.
  • Yes, you must use “smtp.gmail.com” as your SMTP host even if you’re configuring the application for Google Apps. In other words, don’t use “smtp.yourdomain.com”.

I hope this small tutorial saves you some headaches. Cheers :)



2 Responses to “Sending emails with Zend_Mail using Gmail or Google Apps”

  1. Mike Johnson says:

    Hey Mario, This code works great, however… your CMS is converting “=>” to “=>”. If someone were to copy and paste this code directly it would not work.

  2. Mario Awad says:

    Hi Mike, glad to hear the code works for you. Thanks for pointing out the bug, got it fixed now. Cheers :)

Leave a Reply