The smtplib.server.sendmail function in python raises UnicodeEncodeError: 'ascii' codec can't encode character

不想你离开。 提交于 2019-11-29 16:04:06

smtpllib.server's sendmail method expects a bytes inastance; 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'))
{}

This will send this message*:

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.

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'

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!