Python3 'ascii' codec can't encode characters in position 135-136: ordinal not in range(128)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # -*- coding: utf-8 -*- #!/usr/bin/python3 import smtplib gmail_user = 'X@X' gmail_password = 'XXX' from_add = gmail_user to = ["X@X"] subject ="主旨(subject)" body ="內容(content)" email_text ="""\ From: %s To: %s Subject: %s %s """%(from_add,",".join(to), subject, body) try: smtpObj = smtplib.SMTP('smtp.gmail.com', 587) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(gmail_user, gmail_password) smtpObj.sendmail(from_add, to, email_text) smtpObj.close() print('Email sent') except UnicodeEncodeError as err: print('{}'.format(err)) except: print("err") |
我得到了单码编码错误:
"ascii"编解码器无法对位置73-74中的字符进行编码:序号不在范围内(128)
python3默认编码不是"utf-8"吗??
当我运行这个脚本时
实际上是Python3.5.2
当我打印身体的类型时,它是str
但对于python2,错误似乎是asciicode而不是unicode。
谢谢
msg may be a string containing characters in the ASCII range, or a
byte string. A string is encoded to bytes using the ascii codec, and
loneand
characters are converted to
characters. A byte
string is not modified.
您的消息是一个字符串,但包含非ASCII字符;您需要将其编码为字节: