python 中的 smtplib.server.sendmail 函数引发 UnicodeEncodeError: 'ascii' codec can't encode character [英] The smtplib.server.sendmail function in python raises UnicodeEncodeError: 'ascii' codec can't encode character

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

问题描述

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

这是我使用的python代码片段:

irtem = open('irtemplate.txt')数据 = irtem.read().replace('(name)', eng_name).replace('(customer)',cu_name).replace('(sr)', SR_num).replace('(问题)',prob_description).replace('(email)', eng_email).replace('(details)',details_req).replace('(tele)', eng_tele)message_text = 数据message = "发件人: %s
" % fromaddr + "收件人: %s
" % toaddr + "CC:%s
" % ",".join(cc) + "主题:%s
" % message_subject + "
" +消息文本toaddrs = [toaddr] + cc + bccserver.set_debuglevel(1)server.sendmail(fromaddr, toaddrs, message)服务器.退出()

追溯:

回溯(最近一次调用最后一次):文件autoIR.py",第 39 行,在 <module> 中server.sendmail(fromaddr, toaddrs, message)文件/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py",第 855 行,在 sendmail 中msg = _fix_eols(msg).encode('ascii')UnicodeEncodeError: 'ascii' 编解码器无法对字符 'u2019' 进行编码位置 168:序号不在范围内 (128)

解决方案

smtplib.serversendmail 方法需要一个 bytes 实例;如果它得到一个 str,它会尝试将它编码为 ASCII,如果 str 包含任何非 ASCII 字符,则会导致 UnicodeEncodeError.>

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

<预><代码>>>>msg = '你好世界'>>>from_ = 'a@example.com'>>>to_ = 'b@example.com'>>>主题 = '你好'>>>fmt = '发件人:{} 收件人:{} 主题:{} {}'>>>server.sendmail(to_, from_, fmt.format(to_, from_, subject, msg).encode('utf-8')){}

这将发送此消息*:

b'来自:b@example.com'b'收件人:a@example.com'b'主题:你好'b'你好 Wxc3xb8rld'

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

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

<预><代码>>>>从 email.message 导入 EmailMessage>>>em = EmailMessage()>>>em.set_content(味精)>>>em['To'] = to_>>>em['来自'] = from_>>>em['主题'] = 主题>>># 注意调用服务器的 *send_message* 方法>>>server.send_message(em){}

这会发送这条消息;请注意告诉收件人使用的编码的额外标头:

b'Content-Type: text/plain;字符集="utf-8"'b'内容传输编码:8位'b'MIME 版本:1.0'b'收件人:to@example.com'b'来自:from@example.com'b'主题:你好'b'X 对等:::1'''b'你好 Wxc3xb8rld'

* 在单独的终端中运行命令 python -m smtpd -n -c DebuggingServer localhost:1025 以捕获消息数据.

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

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
" % fromaddr + "To: %s
" % toaddr + "CC: 
%s
" % ",".join(cc) + "Subject: %s
" % message_subject + "
" + 
message_text
toaddrs = [toaddr] + cc + bcc
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()

Traceback:

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'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: {}
To: {}
Subject: {}
{}'

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

This will send this message*:

b'From: b@example.com'
b'To: a@example.com'
b'Subject: Hello'
b'Hello Wxc3xb8rld'

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

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

>>> from email.message import EmailMessage
>>> em = EmailMessage()
>>> em.set_content(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: to@example.com'
b'From: from@example.com'
b'Subject: Hello'
b'X-Peer: ::1'
b''
b'Hello Wxc3xb8rld'

* 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' codec can't encode character的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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