# -*- 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")
我收到了UnicodeEncodeError:
' ASCII'编解码器不能对位置73-74中的字符进行编码:序数不在范围(128)
中isn&#39t python3 defult编码是' UTF-8' ??
当我运行此脚本时
实际上是python3.5.2
当我打印身体类型时,它是str
但错误似乎是asciicode而不是python2的unicode
THX
答案 0 :(得分:2)
smtplib.SMTP.sendmail
expects its msg
argument to be str
只包含ascii字符或bytes
:
msg 可以是包含ASCII范围内字符的字符串,或者a 字节串。使用ascii编解码器将字符串编码为字节,并且 单个
\r
和\n
字符将转换为\r\n
个字符。一个字节 字符串未被修改。
您的邮件是一个字符串,但包含非ascii字符;你需要编码为字节:
smtpObj.sendmail(from_add, to, email_text.encode('utf-8'))