在MIMEText中编码头文件

Mar*_*ele 5 python email python-3.x mime-message

我正在使用MIMEText在Python 3.2中从头开始创建一封电子邮件,而且我在主题中使用非ascii字符创建邮件时遇到问题.

例如

from email.mime.text import MIMEText
body = "Some text"
subject = "» My Subject"                   # first char is non-ascii
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = subject                   # <<< Problem probably here
text = msg.as_string()
Run Code Online (Sandbox Code Playgroud)

最后一行给出了错误

UnicodeEncodeError: 'ascii' codec can't encode character '\xbb' in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我如何告诉MIMEText该主题不是ascii?subject.encode('utf-8')根本没有帮助,无论如何我看到人们使用unicode字符串在其他答案中没有问题(参见例如Python - 如何发送utf-8电子邮件?)

编辑:我想补充一点,相同的代码在Python 2.7中没有给出任何错误(认为这并不意味着结果是正确的).

Mar*_*ele 10

我找到了解决方案.包含非ascii字符的电子邮件标头需要根据RFC 2047进行编码.在Python中,这意味着使用email.header.Header而不是标题内容的常规字符串(请参阅http://docs.python.org/2/library/email.header.html).那么编写上面例子的正确方法就是这样

from email.mime.text import MIMEText
from email.header import Header
body = "Some text"
subject = "» My Subject"                   
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject,'utf-8')
text = msg.as_string()
Run Code Online (Sandbox Code Playgroud)

主题字符串将在电子邮件中编码为

=?utf-8?q?=C2=BB_My_Subject?=
Run Code Online (Sandbox Code Playgroud)

python 2.x中前面的代码对我有用的事实可能与邮件客户端能够解释错误编码的头文件有关.