Most of the current mail clients can display html emails without any problems. But still there are cases when html e-mail is not supported. Therefore I would suggest to send emails which contain both – html and plain text as the alternative. Below you can find short example which presents this for Zend Framework 2:
use Zend\Mail\Message, Zend\Mime\Message as MimeMessage, Zend\Mime\Part as MimePart; $htmlPart = new MimePart($bodyHtml); $htmlPart->charset = "UTF-8"; $htmlPart->type = "text/html"; $textPart = new MimePart($bodyText); $textPart->charset = "UTF-8"; $textPart->type = "text/plain"; $body = new MimeMessage(); $body->setParts(array($textPart, $htmlPart)); $message = new Message(); $message->addTo($targetMail, $targetName) ->addFrom($smtpConfig['sender']) ->setSubject($subject) ->setBody($body); $message->getHeaders()->get('content-type')->setType('multipart/alternative');
As you can see we setup Zend\Mime\Part (MimePart) with html content which comes in $bodyHtml
variable. We also set the charset UTF-8 and type for that content text/html. Then the same goes for plain text, but with the type set to text/plain. Afterwards we combine those parts to one object which is Zend\Mime\Message.
We are almost ready. We build Zend\Mail\Message as usually, but we put our MimeMessage as the body.
Final thing is to setup content-type header to multipart/alternative. Otherwise our mail message will not display properly – both parts will be visible in mail client together.