python中的smtplib.server.sendmail函数引发UnicodeEncodeError:'ascii'编解码器无法编码字符

时间:2019-02-24 15:03:20

标签: python python-3.x email character-encoding smtplib

我正在尝试编辑文本文件,然后使用python脚本将其作为电子邮件正文发送,但是我收到了unicode编码错误。经过一些研究,我发现使用.encode('utf-8')方法的解决方案,但这对我没有用,因为sendmail()方法仅发送字符串

这是我使用的python代码段

irtem = open('irtemplate.txt')
data = irtem.read().replace('(name)', eng_name).replace('(customer)', 
cu_name).replace('(sr)', SR_num).replace('(problem)', 
prob_description).replace('(email)', eng_email).replace('(details)', 
details_req).replace('(tele)', eng_tele)


message_text = data
message = "From: %s\r\n" % fromaddr + "To: %s\r\n" % toaddr + "CC: 
%s\r\n" % ",".join(cc) + "Subject: %s\r\n" % message_subject + "\r\n" + 
message_text
toaddrs = [toaddr] + cc + bcc
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()

跟踪:

Traceback (most recent call last):
File "autoIR.py", line 39, in <module>
server.sendmail(fromaddr, toaddrs, message)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 855, in sendmail
msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in 
position 168: ordinal not in range(128)

1 个答案:

答案 0 :(得分:0)

smtpllib.server的sendmail方法要求5.0.3实例;如果获取到bytes,它将尝试将其编码为ASCII,如果str包含任何非ASCII字符,则会生成UnicodeEncodeError

您可以通过自行编码消息来解决此问题:

str

这将发送此消息 *

>>> msg = 'Hello Wørld'
>>> from_ = 'a@example.com'
>>> to_ = 'b@example.com'
>>> subject = 'Hello'

>>> fmt = 'From: {}\r\nTo: {}\r\nSubject: {}\r\n{}'

>>> server.sendmail(to_, from_, fmt.format(to_, from_, subject, msg).encode('utf-8'))
{}

但是,如果您要随消息发送非文本二进制数据,则此解决方法将不起作用。

更好的解决方案是使用电子邮件软件包中的EmailMessage类。

b'From: b@example.com'
b'To: a@example.com'
b'Subject: Hello'
b'Hello W\xc3\xb8rld'

这将发送此消息;请注意额外的标头,告诉接收者所使用的编码:

>>> from email.message import EmailMessage
>>> em = EmailMessage()
>>> em.set_content(fmt.format(to_, from_, subject, msg))
>>> em['To'] = to_
>>> em['From'] = from_
>>> em['Subject'] = subject

>>> # NB call the server's *send_message* method
>>> server.send_message(em)
{}

* 在单独的终端中运行命令b'Content-Type: text/plain; charset="utf-8"' b'Content-Transfer-Encoding: 8bit' b'MIME-Version: 1.0' b'To: b@example.com' b'From: a@example.com' b'Subject: Hello' b'X-Peer: ::1' b'' b'From: b@example.com' b'To: a@example.com' b'Subject: Hello' b'Hello W\xc3\xb8rld' 以捕获消息数据。