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!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
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.