我在 Python 3 中使用 smtplib 通过电子邮件发送 unicode 字符时遇到问题。这在 3.1.1 中失败,但在 2.5.4 中有效:
import smtplib
from email.mime.text import MIMEText
sender = to = 'ABC@DEF.com'
server = 'smtp.DEF.com'
msg = MIMEText('€10')
msg['Subject'] = 'Hello'
msg['From'] = sender
msg['To'] = to
s = smtplib.SMTP(server)
s.sendmail(sender, [to], msg.as_string())
s.quit()
我尝试了文档中的示例,但也失败了。 http://docs.python.org/3.1/library/email-examples.html , 将目录的内容作为 MIME 消息发送示例
有什么建议吗?
最佳答案
关键在the docs :
class email.mime.text.MIMEText(_text, _subtype='plain', _charset='us-ascii')
A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtype is the minor type and defaults to plain. _charset is the character set of the text and is passed as a parameter to the MIMENonMultipart constructor; it defaults to us-ascii. No guessing or encoding is performed on the text data.
所以您显然需要的是不是 msg = MIMEText('€10')
,而是:
msg = MIMEText('€10'.encode('utf-8'), _charset='utf-8')
虽然没有清楚地记录所有内容,sendmail需要一个字节串,而不是 Unicode 串(这是 SMTP 协议(protocol)指定的);查看 msg.as_string()
的两种构建方式中的每一种方式的外观 - 假设“没有猜测或编码”,你的方式仍然有那个欧元字符(并且没有办法用于 sendmail 将其转换为字节串),我的没有(并且在整个过程中明确指定了 utf-8)。
关于Python 3 smtplib 发送带有 unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1429147/