Last Updated: February 25, 2016
·
12.82K
· aimfeld

ZF2: set UTF-8 charset in e-mail header

Displaying special characters correctly (e.g. German umlaute ä, ö, ü) in e-mails can be tricky. The Zend Framework 2 (ZF2) manual suggest calling

Zend\Mail\Message::setEncoding('UTF-8');

This works properly in some e-mail clients (e.g. Gmail), but other clients may mess up the special characters or even fail to display html markup properly. The following ZF2 code sets the content-type e-mail header and UTF-8 charset properly for html e-mails:

/** @var \Zend\Mail\Message $mail */

// Setup mail with html markup
$mail->setSubject($subject);
$html = new \Zend\Mime\Part($text);
$html->type = 'text/html';
$body = new \Zend\Mime\Message;
$body->setParts(array($html));
$mail->setBody($body);

// Set UTF-8 charset
$headers = $mail->getHeaders();
$headers->removeHeader('Content-Type');
$headers->addHeaderLine('Content-Type', 'text/html; charset=UTF-8');

7 Responses
Add your response

Hello, and thanks for this info!
But there's a small mistake at the end,

the line "$mail->getHeaders();"
should be "$headers = $mail->getHeaders();" ;-)

I've tried your answer, but now, gmail put my mail directly in the spam section... There must be something wrong with the header...
Any clue?

over 1 year ago ·

Thanks, I fixed the code snippet. I also work with gmail and I have never experienced the spam problem you mention. I suggest you compare mail headers and see, if other things than 'Content-Type' have changed...

over 1 year ago ·

@elpinois Here's a really cool tool for testing why your mails are getting marked as spam: http://www.emailspamtest.com/. Please report whether it has anything to do with the Content-Type header...

over 1 year ago ·

@elpinois This tool is actually better for testing for spam: http://isnotspam.com/

over 1 year ago ·

Thanks for the hint.

You might also just add the charset to the type when you set it first time around, instead of removing the header and adding it again:

$html->type = 'text/html; charset=UTF-8'</code>

(or do it by appending charset to typetext constant)

$html->type = Mime::TYPE_HTML . "; charset=UTF-8"</code>

(note: no trailing ";" after UTF-8)

over 1 year ago ·

actually the Zend\Mime\Part class has both type and charset properties, so the correct way would be

use Zend\Mime;

$html = new Mime\Part($text);
$html->type = Mime\Mime::TYPE_HTML;
$html->charset = 'utf-8';
over 1 year ago ·

Don't forget to set headers back $mail->setHeaders($headers).

over 1 year ago ·