Why Gmail doesn't display my RFC 2047-encoded From header?
Question
My Python application uses email.header.Header (http://docs.python.org/2/library/email.header.html ) to encode all headers of outgoing email (including From header), just like indicated here: Encoding mail subject (SMTP) in Python with non-ASCII characters
It works perfectly for ASCII sender names, but for senders like
Adrian Płonka <pokemon@myservice.com>
it produces
From: =?utf-8?q?Adrian_P=C5=82onka_=3Cpokemon=40myservice=2Ecom=3E?=
Unfortunately, Gmail apparently doesn't like this way of encoding as it displays the sender as (unknown) and marks the whole message as Spam.
How do I properly encode non-ASCII senders?
Solution
The proper way to encode that is
From: =?utf-8?q?Adrian_P=C5=82onka?= <pokemon@myservice.com>
That is, only the name part, not the actual email terminus, may be RFC2047-encoded.
OTHER TIPS
The most elegant way I can think of in order to achieve the outcome from @tripleee's answer would be:
message['From'] = formataddr((charset.header_encode('Adrian Płonka'), 'pokemon@myservice.com'))
where charset
is an email.charset.Charset
object, I created with:
charset = email.charset.Charset()
charset.body_encoding = email.charset.QP
charset.header_encoding = email.charset.QP
charset.input_charset = 'utf-8'
charset.output_charset = 'utf-8'
charset.input_codec = 'utf-8'
charset.output_codec = 'utf-8'
It displays correctly with Gmail as well as with other providers.
This was non-trivial for me to find, hope it helps...