Creating HTML E-mails in Zend Framework 2 with Zend_Mail + Zend_Mime

user521990 picture user521990 · Oct 16, 2012 · Viewed 16.7k times · Source

Zend framework changed the Zend_Mail object so it no longer has the setBodyHtml() method to create HTML e-mails.

Does anyone know how to create an HTML e-mail with the ZF2 Mail component? So far I have tried:

$html = new \Zend\Mime\Part($htmlText);
$html->type = \Zend\Mime\Mime::TYPE_HTML;
$html->disposition = \Zend\Mime\Mime::DISPOSITION_INLINE;
$html->encoding = \Zend\Mime\Mime::ENCODING_QUOTEDPRINTABLE;
$html->charset = 'iso-8859-1';

$body = new \Zend\Mime\Message();
$body->addPart($html);

$message = new \Zend\Mail\Message();
$message->setBody($body);
$message->addTo('[email protected]', 'User1');
$message->addFrom('[email protected]', 'User2');
$message->setSubject('Test');

The resulting email is:

MIME-Version: 1.0

Content-Type: text/html; charset=iso-8859-1

Content-Transfer-Encoding: quoted-printable

Content-Disposition: inline

From: XYZ

Report of last months log files=0A=09=09=09=0A=09=

=>09=09=0A=09=09=09Test=0A =09=09=09=0A=09=09=09

l>

Answer

user521990 picture user521990 · Oct 17, 2012

It turns out there is a issue as I have found with the \Zend\Mail\Header component.

I am using a linux based machine to host my php machine which means each header line in an email should have "\r" ONLY appended to it. For Windows it is "\r\n".

The constant EOL in the \Zend\Mail\Header file is set at "\r\n" causing all the headers to appear in the e-mail if sent from a linux machine.

The best practice here is to use the PHP_EOL constant which automatically detects the platform and uses the CORRECT end of line code.

To fix this:

You need to update your \Zend\Mail\Header EOL constant to equal PHP_EOL. Also if using UTF-8 you must make sure it is the last thing that is called on your message. It must be done after the body is set.

I put in a ticket to ZF2 2.0 team to look at it

This is a working example:

    $html = '' //my html string here

    $m = new \Zend\Mail\Message();
    $m->addFrom('[email protected]', 'Joe Schmo')
      ->addTo('[email protected]', 'Ally Joe')
      ->setSubject('Test');

    $bodyPart = new \Zend\Mime\Message();

    $bodyMessage = new \Zend\Mime\Part($html);
    $bodyMessage->type = 'text/html';

    $bodyPart->setParts(array($bodyMessage));

    $m->setBody($bodyPart);
    $m->setEncoding('UTF-8');

             //send your message now