python - MIMEText 中的标题编码

标签 python email python-3.x mime-message

我在 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/

相关文章:

python - 将大型视频文件上传到 Google App Engine

python - 如何在Python中拆分表中的两列

python - syslog 正在工作,但 SysLogHandler 不工作

python - 哪个 XML 解析器具有最易读的错误报告?

python - 调用多个其他脚本的脚本由于未定义的函数而出错

python - 无法在 GAE 中添加来自其他域的电子邮件地址

java - 当域名包含连字符时,电子邮件地址验证失败

linux - 一种通过避免 = 符号自动断开长行来逐行阅读电子邮件的脚本方法

python-3.x - 如何模拟 Python 类的对象?

python - 安装 Raqm (Libraqm) Windows 10