Sending e-mails in Zend Framework 2 is quite easy and requires small amount of code. Below example presents sending multipart e-mails (containing plain text and html at once):
$htmlPart = new Zend\Mime\Part($bodyHtml); $htmlPart->charset = "UTF-8"; $htmlPart->type = Zend\Mime\Mime::TYPE_HTML; $textPart = new Zend\Mime\Part($bodyText); $textPart->charset = "UTF-8"; $textPart->type = Zend\Mime\Mime::TYPE_TEXT; $body = new Zend\Mime\Message(); $body->setParts(array($textPart, $htmlPart)); $message = new Zend\Mail\Message(); $message->addTo($targetMail, $targetName) ->addFrom($fromMail, $fromName) ->setSubject($subject) ->setBody($body) ->setEncoding("UTF-8"); $transport = new Sendmail(); $transport->send($message);
That’s it. It will create simple message and send it using sendmail.
Long line issue – symptoms
If you are sending e-mail over smtp server (using Zend\Mail\Transport\Smtp) you can see that mail body will contain exclamation marks in random positions of e-mail.
If you are sending e-mail over sendmail (using Zend\Mail\Transport\Sendmail) you can get an exception during sending.
Reason
The main reason of such situation are long lines in the mail body.
Solution
How to proceed in such case? We shouldn’t break lines manually because our e-mails will look strange in different mail clients.
The solution is to add base64 encoding to each mime part of e-mail. It does everything for us and error will gone.
Below is the final code to build mime parts of e-mail:
$htmlPart = new Zend\Mime\Part($bodyHtml); $htmlPart->charset = "UTF-8"; $htmlPart->type = Zend\Mime\Mime::TYPE_HTML; $htmlPart->encoding = Zend\Mime\Mime::ENCODING_BASE64; $textPart = new Zend\Mime\Part($bodyText); $textPart->charset = "UTF-8"; $textPart->type = Zend\Mime\Mime::TYPE_TEXT; $textPart->encoding = Zend\Mime\Mime::ENCODING_BASE64;
So the only thing is to add encoding for each part: Zend\Mime\Mime::ENCODING_BASE64.