Send Mail with Zend Framework

Simple, but Doesn’t Work!

It may sound strange, because all this is quite well documented in the Zend Framework documentation. Indeed it’s very very simple and all is done only by few lines of code.

$mail = new Zend_Mail();
$mail->setFrom('sender@example.com');
$mail->setBodyHtml('some message - it may be html formatted text');
$mail->addTo('recipient@example.com', 'recipient');
$mail->setSubject('subject');
$mail->send();

Even it look simple though, it may not work on your localhost while you’re trying to make it work! Because you’ve to have sendmail setup. And in Zend Framework sendmail is the default transport protocol for sending mails.

What You Have to Do to Make it Work?

Actually you’ve simply to add a transport protocol, just like that:

$tr = new Zend_Mail_Transport_Smtp('smtp.example.com',
                    array('auth' => 'login',
                             'username' => 'username',
                             'password' => 'password'));
Zend_Mail::setDefaultTransport($tr);

Where Did I Get These?

Well look at your favorite mail account you probably use every day. It may be hosted in GMail or wherever, but there are some configurations you have to port under Zend’s code and everything will be just fine until you develop the app!

6 thoughts on “Send Mail with Zend Framework

  1. For local testing I use gmail as my outgoing smtp server

    require_once ‘Zend/Mail.php’;
    require_once ‘Zend/Mail/Transport/Smtp.php’;

    try {

    $configMail = array(
    ‘auth’ => ‘login’,
    ‘username’ => ‘youremail@gmail.com’,
    ‘password’ => ‘password’,
    ‘ssl’ => ‘ssl’,
    ‘port’ => 465
    );
    $mailTransport = new Zend_Mail_Transport_Smtp(‘smtp.gmail.com’,$configMail) ;
    Zend_Mail::setDefaultTransport($mailTransport);
    // defines gmail smtp infrastructure as default for any email message originated by Zend_Mail.

    $mail = new Zend_Mail();
    $mail->setBodyText(‘testing gmail’);
    $mail->setFrom(‘youremail@domain.com’, ‘your name’);
    $mail->addTo(‘sendto@domain.com’, ‘Me’);
    $mail->setSubject(‘TestSubject—–‘);
    $mail->send();

    } catch (Zend_Exception $e) {
    // Here you can log an Zend_Mail exceptions
    }

  2. The first piece of code actually worked for me, but to be fair, I had my postfix configured to use an external SMTP provider, so if configured well, it will work 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *