Python 3 smtplib 发送带有 unicode 字符

标签 python email unicode python-3.x smtplib

我在 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/

相关文章:

php - 使用 PHP 从 Gmail 获取所有邮件

java - 如何实际配置 Microsoft Graph API for Mail

python - 如何在 python 中处理 unicode 语言

python - 打印对象和 unicode,背后是什么?好的指导方针是什么?

python - NameError 即使在上面的行中有直接的、无条件的赋值

python - Seaborn tsplot 不显示数据

删除文本文件中特定行的Python程序

python - 从字典列表创建嵌套列表

python - 如何使 MLModel 在 Swift CoreML 中可更新?

html - Android - 如何从包含 css 和 html 的文件创建电子邮件正文?