UnicodeDecodeError:'ascii'编解码器无法解码 - Python

时间:2016-04-29 19:40:05

标签: python email unicode smtp ascii

尝试使用standard Python example

发送电子邮件时收到以下错误消息
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 27: ordinal not in range(128)

以下是代码:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

任何想法如何克服这个?

2 个答案:

答案 0 :(得分:0)

如果unicode对您不重要,您可以尝试以下方法:

import unicodedata

str = fp.read()
normalized_message = unicodedata.normalize('NFKD', unicode(str, 'utf-8')).encode('ascii','ignore')
msg = MIMEText(normalized_message)

这会将所有unicode转换为最接近的ASCII等效值。

答案 1 :(得分:0)

代码示例明确说明:

# For this example, assume that
# the text file contains only ASCII characters.

即,如果输入包含非ascii字符,则不会起作用。 To send email that may contain non-ascii characters, use this answer