python中的smtplib.server.sendmail函数引发UnicodeEncodeError:'ascii'编解码器无法编码字符 [英] The smtplib.server.sendmail function in python raises UnicodeEncodeError: 'ascii' codec can't encode character

查看:385
本文介绍了python中的smtplib.server.sendmail函数引发UnicodeEncodeError:'ascii'编解码器无法编码字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to edit a text file then send it as email body using a python script but im getting the unicode encoding error. After some research i found the solution as using the method .encode('utf-8') but this doesn't serve me as the sendmail() method only sends strings

以下是使用以下代码的python代码段:

Here is the python code snippet Im using:

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)


推荐答案

smtplib.server sendmail 方法期望一个 bytes 实例;如果它得到 str ,它将尝试将其编码为ASCII,如果 UnicodeEncodeError > str 包含任何非ASCII字符。

smtplib.server's sendmail method expects a bytes instance; if it gets a str it tries to encode it to ASCII, resulting in a UnicodeEncodeError if the str contains any non-ASCII characters.

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

You can workaround this by encoding the message yourself:

>>> 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'))
{}

这将发送此消息 *

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

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

However this workaround will not work if you want to send non-text binary data with your message.

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

A better solution is to use the EmailMessage class from the email package.

>>> 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)
{}

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

This sends this message; note the extra headers telling the recipient the encoding used:

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'

* 运行命令 python -m smtpd -n -c在另一个终端中的DebuggingServer localhost:1025 捕获消息数据。

* Run the command python -m smtpd -n -c DebuggingServer localhost:1025 in a separate terminal to capture the message data.

这篇关于python中的smtplib.server.sendmail函数引发UnicodeEncodeError:'ascii'编解码器无法编码字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆