flask-mail icon indicating copy to clipboard operation
flask-mail copied to clipboard

Incorrect encoding of (unicode) headers in Python 3

Open roganov opened this issue 9 years ago • 4 comments

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

roganov avatar Jun 11 '15 06:06 roganov

The issue might be related to https://github.com/mattupstate/flask-mail/issues/88

roganov avatar Jun 11 '15 10:06 roganov

I met same problem. Isn't it bug?

toughrogrammer avatar Apr 19 '16 13:04 toughrogrammer

This is very annoying and should be recognized as a bug, or at least documented in some way.

Guibod avatar Dec 14 '18 10:12 Guibod

I have the same problem. And I solved the problem using @roganov 's method. Thank you My subject is 【二手车每月拍卖数据】数据导出20190305

eden-wang avatar Mar 06 '19 09:03 eden-wang

We use Python's email.header. If they're producing incorrect values, that will need to be reported to them.

davidism avatar May 23 '24 17:05 davidism