Zend_Mail

Posted by Federico in Components

Description

Zend_Mail, supported by Zend_Mime, creates and sends e-mail messages with the format text or HTML. Zend_Mime is a support set for handling multipart MIME messages. Zend_Mail allows e-mail to be sent in an easy form while preventing mail injection.

General Usage

Example: Simple email with Zend_Mail

$mail = new Zend_Mail();
$mail->setBodyText("This is the text of the mail");
$mail->setFrom("somebody@example.com", "Some Sender");
$mail->addTo("somebody_else@example.com", "Some Recipient");
$mail->setSubject("Test Subject");
$mail->send();

For security reasons, Zend_Mail filters all header fields to prevent header injection with newline (\n) characters. You also can use most methods of the Zend_Mail object with a convenient fluent interface. A fluent interface means that each method returns a reference to the object on which it was called, so you can immediately call another method.

Example: Zend_Mail fluent interface

$mail = new Zend_Mail();
$mail->setBodyText("This is the text of the mail.")
    ->setFrom("somebody@example.com’, ‘Some Sender")
    ->addTo("somebody_else@example.com", "Some Recipient")
    ->setSubject("TestSubject")
    ->send();

Zend_Mail messages can be sent via SMTP, so Zend_Mail_Transport_SMTP needs to be created and registered with Zend_Mail before the send() method is called.

Example: Sending email via SMTP

$tr = new Zend_Mail_Transport_Smtp("mail.example.com")
Zend_Mail::setDefaultTransport($tr);

$mail = new Zend_Mail();
$mail->setBodyText("This is the text of the mail.");
$mail->setFrom("somebody@example.com", "Some Sender");
$mail->addTo("somebody_else@example.com", "Some Recipient");
$mail->setSubject("Test Subject");
$mail->send();

Example: Sending multiple emails per SMTP connection.

$mail = new Zend_Mail();
$tr = new Zend_Mail_Transport_Smtp("mail.example.com");
Zend_Mail::setDefaultTransport($tr);

$tr->connect();
for ($i = 0; $i < 5; $i++) {
        $mail->setBodyText("This is the text of the mail.");
        $mail->setFrom("somebody@example.com", "Some Sender");
        $mail->addTo("somebody_else@example.com", "Some Recipient");
        $mail->setSubject("Test Subject");
        $mail->send();
}
$tr->disconnect();

To send an e-mail in HTML format, set the body using the method setBodyHTML() instead of setBodyText(). The MIME content type will automatically be set to text/html then. If you use both HTML and Text bodies, a multipart/alternative MIME message will automatically be generated:

Example: Sending an HTML email

$mail = new Zend_Mail();
$mail->setBodyText("My Nice Test Text");
$mail->setBodyHtml("My Nice Test Text");
$mail->setFrom("somebody@example.com", "Some Sender");
$mail->addTo("somebody_else@example.com", "Some Recipient");
$mail->setSubject("TestSubject");
$mail->send();

Learn more about Zend_Mail


Do you have something to say? Say it below.