Python 3 smtplib用unicode字符发送 [英] Python 3 smtplib send with unicode characters
问题描述
我在Python 3中使用smtplib发送电子邮件发送unicode字符问题。3.1.1中失败,但在2.5.4中有效:
I'm having a problem emailing unicode characters using smtplib in Python 3. This fails in 3.1.1, but works in 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消息示例发送
I tried an example from the docs, which also failed. http://docs.python.org/3.1/library/email-examples.html, the Send the contents of a directory as a MIME message example
任何建议?
推荐答案
关键在文档:
class email.mime.text.MIMEText(_text, _subtype='plain', _charset='us-ascii')
MIMENonMultipart的子类,
MIMEText类用于创建主要类型文本的MIME
对象。 _text是
有效负载的字符串。 _subtype
是次要类型,默认为
plain。 _charset是文本的字符集
,并作为
参数传递给MIMENonMultipart
构造函数;它默认为我们 - 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.
所以你需要的是清楚的, em>不 msg = MIMEText('€10')
,而是:
So what you need is clearly, not msg = MIMEText('€10')
, but rather:
msg = MIMEText('€10'.encode('utf-8'), _charset='utf-8')
虽然并没有清楚记录, sendmail 需要一个字节串,而不是一个Unicode(这是SMTP协议指定的);看看什么 msg.as_string()
看起来像为建立它的两种方式 - 给定没有猜测或编码,你的方式仍然有欧元字符在那里(没有办法让sendmail把它变成一个测试),我的(不是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).
这篇关于Python 3 smtplib用unicode字符发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!