在MIMEText中编码头文件

时间:2013-04-18 13:40:52

标签: 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()

最后一行给出了错误

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中没有给出任何错误(认为这并不意味着结果是正确的)。

3 个答案:

答案 0 :(得分: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()

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

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

以前的代码在python 2.x中工作的事实可能与邮件客户端能够解释错误编码的头文件有关。

答案 1 :(得分:0)

         Esta funsion manda un email a un solo correo si alguien quiere la funsión que          mande a varios email tambien la tengo.
         text = ('Text')
         mensaje = MIMEText(text,'plain','utf-8')
         mensaje['From']=(remitente)
         mensaje['Subject']=('Asunto')
         mailServer = smtplib.SMTP('xxx.xxx.mx')
         mailServer.ehlo()
         mailServer.starttls()
         mailServer.ehlo()

         mailServer.sendmail(remitente,destinatario, mensaje.as_string())
                            mailServer.close()

答案 2 :(得分:0)

我发现可以替换

msg['Subject'] = subject

使用

msg.add_header('Subject', subject)

用于显示UTF-8。如果需要另一个字符集,也可以这样做。尝试help(msg.add_header)查看有关该文档的信息(将值subject替换为包含三个元素的元组:(字符集,语言,值)。

无论如何,这似乎比其他方法简单一些-因此,我想我会提到它。我决定尝试此操作,因为add_header似乎对'reply-to'头的工作更多,而不仅仅是执行msg [“ reply-to”] = your_reply_to_email。因此,我认为对于主题也可能会更好—并且文档说它默认情况下支持UTF-8(我测试了并且有效)。