# -*- 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")
我得到了UnicenCodeError:
'ascii'编解码器无法在位置73-74中编码字符:不在范围内(128(
python3 defult编码是'utf-8'??
我运行此脚本
它实际上是python3.5.2
当我打印身体的类型时,它是str
但是,错误似乎不是python2
的unicodethx
smtplib.SMTP.sendmail
期望其 msg
参数是仅包含ascii字符或 bytes
的 str
:
msg 可以是包含ASCII范围内字符的字符串,或 字节字符串。使用ASCII编解码器编码字符串,并 唯一的
r
和n
字符转换为rn
字符。字节 字符串未修改。
您的消息是字符串,但包含非ASCII字符;您需要编码为字节:
smtpObj.sendmail(from_add, to, email_text.encode('utf-8'))