Python 3 smtplib使用unicode字符发送

foo*_*ion 8 python email unicode smtplib python-3.x

我在使用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()
Run Code Online (Sandbox Code Playgroud)

我尝试了一些来自文档的例子,但也失败了. http://docs.python.org/3.1/library/email-examples.html,将目录内容作为MIME消息示例发送

有什么建议?

Ale*_*lli 13

关键在于文档:

class email.mime.text.MIMEText(_text, _subtype='plain', _charset='us-ascii')
Run Code Online (Sandbox Code Playgroud)

MIMENonMultipart的子类,MIMEText类用于创建主要类型文本的MIME对象._text是有效负载的字符串._subtype是次要类型,默认为plain._charset是文本的字符集,作为参数传递给MIMENonMultipart构造函数; 它默认为us-ascii.不对文本数据执行猜测或编码.

所以你需要的是显而易见的,而不是 msg = MIMEText('€10'),而是:

msg = MIMEText('€10'.encode('utf-8'), _charset='utf-8')
Run Code Online (Sandbox Code Playgroud)

虽然没有明确记录,sendmail需要一个字节串,而不是Unicode字符串(这是SMTP协议指定的); 看看msg.as_string()建立它的两种方式中的每一种看起来是什么样的 - 鉴于"没有猜测或编码",你的方式仍然有那个欧元字符(并且sendmail没有办法把它变成字节串),我的没有't(并且utf-8在整个过程中明确指定).