Sending an HTML with text alternative email with Zend\Mail

Sending a multi-part email with Zend\Mail is easy enough, but if you want to send an HTML email with a text alternative, you need to remember to set the content-type in the headers to multipart/alternative. As this is the second time I had to work this out, I'm noting it here for the next time I forget!

use Zend\Mail;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;
 
 
function sendMail($htmlBody, $textBody, $subject, $from, $to)
{
    $htmlPart = new MimePart($htmlBody);
    $htmlPart->type = "text/html";
 
    $textPart = new MimePart($textBody);
    $textPart->type = "text/plain";
 
    $body = new MimeMessage();
    $body->setParts(array($textPart, $htmlPart));
 
    $message = new Mail\Message();
    $message->setFrom($from);
    $message->addTo($to);
    $message->setSubject($subject);
 
    $message->setEncoding("UTF-8");
    $message->setBody($body);
    $message->getHeaders()->get('content-type')->setType('multipart/alternative');
 
    $transport = new Mail\Transport\Sendmail();
    $transport->send($message);
}

One Response to “Sending an HTML with text alternative email with Zend\Mail”

  1. 1 John Nicholls

    Thanks Rob... just what I was looking for. ZF2 documentation is improving, but lacks many real world examples like this.

The views expressed in these comments are not the views of the publisher. However, we believe in the rights of others to express their legitimate views and concerns. Any legitimate complaint emailed to rob@akrabat.com will be seriously considered and the post reviewed as desirable and necessary.