想用Python的SMTP给自己发邮件试试,在txt中随机选取一句话发送(中文),但是显示UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-13: ordinal not in range(128),
试了网上的方法(python 3):
import importlib
importlib.reload(sys)
还是无法解决
想用Python的SMTP给自己发邮件试试,在txt中随机选取一句话发送(中文),但是显示UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-13: ordinal not in range(128),
试了网上的方法(python 3):
import importlib
importlib.reload(sys)
还是无法解决
用下面的可以发送中文,题主那段代码用ascii编码中文内容会出错
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from_addr = 'xxx@xxx.xxx'
password = 'xxxx'
to_addr = 'xxx@xx.xxx'
smtp_server = 'xx.xx.xx'
msg = MIMEText('使用python发送邮件测试', 'plain', 'utf-8')
msg['From'] = Header('张三')
msg['To'] = Header('李四')
subject = 'Python SMTP 邮件测试'
msg['Subject'] = Header(subject, 'utf-8')
try:
smtpobj = smtplib.SMTP_SSL(smtp_server)
smtpobj.connect(smtp_server, 465)
smtpobj.login(from_addr, password)
# 发送邮件
smtpobj.sendmail(from_addr, to_addr, msg.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("无法发送邮件")
finally:
# 关闭服务器
smtpobj.quit()