8

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

有什么建议么?

4

2 回答 2

13

The key is in 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.

So what you need is clearly, not msg = MIMEText('€10'), but rather:

msg = MIMEText('€10'.encode('utf-8'), _charset='utf-8')

While not all that clearly documented, sendmail needs a byte-string, not a Unicode one (that's what the SMTP protocol specifies); look to what msg.as_string() looks like for each of the two ways of building it -- given the "no guessing or encoding", your way still has that euro character in there (and no way for sendmail to turn it into a bytestring), mine doesn't (and utf-8 is clearly specified throughout).

于 2009-09-16T02:00:56.690 回答
2
于 2009-09-15T19:39:43.400 回答