我在 Python 3.2 中使用 MIMEText 从头开始创建电子邮件,但在创建主题中包含非 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()
最后一行给出了错误
UnicodeEncodeError: 'ascii' codec can't encode character '\xbb' in position 0: ordinal not in range(128)
如何告诉 MIMEText 主题不是 ascii ? subject.encode('utf-8')
一点用都没有,而且我见过有人使用 unicode 字符串,在其他答案中没有问题(例如参见 Python - How to send utf-8 e-mail? )
编辑:我想补充一点,相同的代码在 Python 2.7 中没有给出任何错误(认为这并不意味着结果是正确的)。
最佳答案
我找到了解决方案。 包含非 ascii 字符的电子邮件 header 需要按照 RFC 2047 进行编码. 在 Python 中,这意味着使用 email.header.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()
主题字符串将在电子邮件中编码为
=?utf-8?q?=C2=BB_My_Subject?=
之前的代码在 python 2.x 中对我有用的事实可能与邮件客户端能够解释错误编码的 header 有关。
关于python - MIMEText 中的标题编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16084605/