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 MailMessage();
$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);
}
Thanks Rob… just what I was looking for. ZF2 documentation is improving, but lacks many real world examples like this.