在MIMEText中编码头文件

问题描述 投票:5回答:3

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

python email python-3.x mime-message
3个回答
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中前面的代码对我有用的事实可能与邮件客户端能够解释错误编码的头文件有关。


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

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(我测试过,并且它有效)。

© www.soinside.com 2019 - 2024. All rights reserved.