使用unicode字符发送Python 3 smtplib

2024-05-23 16:54:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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消息示例发送

有什么建议吗?


Tags: totextfromimportcomserveremaildef
3条回答

密钥在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协议指定的);看看构建它的两种方法中的每一种方法的msg.as_string()是什么样子的——考虑到“没有猜测或编码”,您的方法中仍然有那个欧元字符(sendmail也没有办法将其转换为byte string),我的没有(而且utf-8在整个过程中都有明确的说明)。

根据docsMIMEText_charset参数默认为us-ascii。因为不是来自美国ascii集,所以它不起作用。

您尝试过的文档中的示例清楚地说明:

For this example, assume that the text file contains only ASCII characters.

您可以对消息使用^{}方法来研究字符集,顺便说一下还有.set_charset

Gus Mueller也有类似的问题:http://bugs.python.org/issue4403

相关问题 更多 >