MIMEText中头文件的编码

MIMEText中头文件的编码

本文介绍了MIMEText中头文件的编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MIMEText在Python 3.2中从头开始创建一个电子邮件,我无法在主题中创建非ASCII字符的消息。

I'm using MIMEText to create an email from scratch in Python 3.2, and I have trouble creating messages with non-ascii characters in the subject.

例如

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字符串,在其他答案中没有问题(参见例如 )

How do I tell MIMEText that the subject is not ascii ? subject.encode('utf-8') doesn't help at all, and anyway I've seen people using unicode strings with no problems in other answers (see for example Python - How to send utf-8 e-mail?)

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

I'd like to add that the same code doesn't give any error in Python 2.7 (thought that doesn't mean that the result is correct).

推荐答案

我找到了解决方案。
包含非ASCII字符的电子邮件标头需要根据进行编码。
在Python中,这意味着使用email.header.Header而不是标题内容
的常规字符串(请参阅)。
正确的方法来写上面的例子然后是

I found the solution.Email headers containing non ascii characters need to be encoded as per RFC 2047.In Python this means using email.header.Header instead of a regular string for header content(see http://docs.python.org/2/library/email.header.html).The right way to write the above example is then

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()

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

The subject string will be encoded in the email as

=?utf-8?q?=C2=BB_My_Subject?=

事实上,python 2.x以前的代码正在为我工​​作可能与邮件客户端能够解释错误编码的标题有关。

The fact the in python 2.x the previous code was working for me is probably related to the mail client being able to interpret the wrongly encoded header.

这篇关于MIMEText中头文件的编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 11:20