flask-mail
flask-mail copied to clipboard
Incorrect encoding of (unicode) headers in Python 3
The policy
setting affects the way the headers are encoded, and as a result some emails are not displayed correctly in (at least) Gmail.
Consider this example:
msg = MIMEMultipart('alternative')
msg['Subject'] = Header("Добавить в рассыку dev@ Имя Фамилия", 'utf8').encode()
msg['From'] = Header('Имя Фамилия (Whatever)', 'utf8').encode() + ' <[email protected]>'
msg['To'] = '[email protected]'
msg.attach(MIMEText('text', 'plain'))
msg.attach(MIMEText('html', 'html'))
from email import policy
msg.policy = policy.SMTP
msg.as_bytes()
The resulting 'Subject' header is encoded as such:
'Subject: =?utf-8?b?0JTQvtCx0LDQstC40YLRjA==?= =?utf-8?q?=D0=B2?=\r\n =?utf-8?b?0YDQsNGB0YHRi9C60YM=?= dev@ =?utf-8?b?0JjQvNGP?=\r\n =?utf-8?b?0KTQsNC80LjQu9C40Y8=?=\r\n'
You can see that the subject was split on every space and each chunk was encoded separately. As a result, Gmail displays the subjects without spaces whatsoever.
With no policy
set:
'Subject: \n =?utf8?b?0JTQvtCx0LDQstC40YLRjCDQsiDRgNCw0YHRgdGL0LrRgyBkZXZAINCY0LzRjyA=?=\n =?utf8?b?0KTQsNC80LjQu9C40Y8=?=\n'
In this case, Gmail displays the subject as expected.
I don't know whether this is a bug or not, but I reckon there should be a way to customize the email policy in flask-mail.
For now I'm monkey-patching the flask_mail module:
import flask_mail; flask_mail.message_policy = None
The issue might be related to https://github.com/mattupstate/flask-mail/issues/88
I met same problem. Isn't it bug?
This is very annoying and should be recognized as a bug, or at least documented in some way.
I have the same problem. And I solved the problem using @roganov 's method. Thank you
My subject is 【二手车每月拍卖数据】数据导出20190305
We use Python's email.header
. If they're producing incorrect values, that will need to be reported to them.