Home / Sending email with Zend_Mail

Sending email with Zend_Mail

The Zend Framework is a PHP framework with many individual components that do not require you to use the whole framework. In this post I will look at how to send an email using the Zend Framework’s Zend_Mail component.

Before using any component from the Zend Framework you need to add the path of the framework to your include path. This is because the various component require other library files and assume the "Zend" directory is already in the include path.

Basic usage

Having done this, the example below shows the basic usage of sending an email using Zend_Mail:

require_once('Zend/Mail.php');

$mail = new Zend_Mail();
$mail->setBodyText('This is an example message body');
$mail->setFrom('chris@example.com', 'Chris Hope');
$mail->addTo('john@example.com', 'John Smith');
$mail->setSubject('This is an example subject');
$mail->send();

Setting the HTML body text

If you want to add an HTML version of the message body you can do the following.

$mail->setBodyHtml($html);

Note that you don’t have to have both an HTML body and a plain text body but you must specify at least one of them. If you don’t you’ll get a nasty error message along these lines:

Fatal error: Uncaught exception 'Zend_Mail_Transport_Exception' with message 'No body specified' in /path/to/Zend/Mail/Transport/Abstract.php:284
Stack trace:
#0 /path/to/Zend/Mail/Transport/Abstract.php(313): Zend_Mail_Transport_Abstract->_buildBody()
#1 /path/to/Zend/Mail.php(720): Zend_Mail_Transport_Abstract->send(Object(Zend_Mail))
#2 /path/to/test_script.php(15): Zend_Mail->send()
#3 {main} thrown in /path/to/Zend/Mail/Transport/Abstract.php on line 284

To, CC and BCC recipients

You can also specify multiple "to" recipients by calling the addTo() method multiple times:

$mail->addTo('john@example.com', 'John Smith');
$mail->aadTo('jane@example.com', 'Jane Doe');

And also CC and BCC recipienrs like so:

$mail->addCc('john@example.com', 'John Smith');
$mail->addBcc('jane@example.com');

The addTo, setFrom and addCc all take a second optional parameter in which you can specify the person’s name, the first parameter being to set their email address. The addBcc method only has the email address parameter because the name is not set in the actual email for Bcc recipients.

Chaining it altogether

It’s possible to chain the whole call together and send an email as follows instead. A lot of this style comes down to personal preference:

$mail = new Zend_Mail();
$mail->setBodyText('this is a test')
    ->setFrom('chris@example.com', 'Chris Hope')
    ->addTo('chris@example.com', 'Chris Hope')
    ->setSubject('This is a test subject')
    ->send();

Further reading

In future posts I will look at adding attachments to emails using Zend Framework Zend_Mail and specifying the transport to use i.e. sendmail vs an SMTP server.