我正在尝试编辑文本文件,然后使用python脚本将其作为电子邮件正文发送,但是我收到了unicode编码错误。经过一番研究后,我发现使用.encode(’utf-8’)方法的解决方案,但这对我没有用,因为sendmail()方法仅发送字符串
这是Im使用的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)
smtplib.server的sendmail方法需要一个bytes实例;如果获取到,str则尝试将其编码为ASCII,UnicodeEncodeError如果str包含任何非ASCII字符,则生成。
smtplib.server
bytes
str
UnicodeEncodeError
您可以通过自己编码消息来解决此问题:
>>> 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'
但是,如果您想随消息发送非文本二进制数据,则此解决方法将不起作用。
更好的解决方案是使用电子邮件包中的EmailMessage类。
>>> 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'
*python -m smtpd -n -c DebuggingServer localhost:1025在单独的终端中运行命令以捕获消息数据。
python -m smtpd -n -c DebuggingServer localhost:1025