I'm trying to send an email and have a small problem with the sender address in the header part of the message contents.
Basically, this is what I want to have in the headers:
From: "Real Name" <test@example.com>
And this is what I do (Python 3.5):
message = email.mime.text.MIMEText(body)
message.add_header('From', from_hdr)
It works as expected for ASCII, but not for UTF-8.
Given a non-ASCII name like "Strángé Nämé" <test@example.com>
the input gets encoded by add_header()
:
If the value contains non-ASCII characters ..... it is automatically encoded in RFC 2231 format using a CHARSET of utf-8 and a LANGUAGE of None.
The problem is that the whole string - not only the real name - is encoded. The result looks like a single string: =?utf-8?.....?=
and the original format is lost. The mail server adds the apparently missing domain to it and the damage is done.
The sender is then shown (decoded by the recipient's email program) as:
"\"Strángé Nämé\" <test@example.com>"@server.example.com
I have tried to split the address using email.utils.parseaddr()
and encode only the real name part with email.utils.encode_rfc2231()
but this did not help.
I'm avoiding UTF-8 in the Form: field for now, don't know how to handle it properly. Could you please help?