首页 文章

Python3 'ascii'编解码器无法对135-136位置的字符进行编码:序号不在范围内(128)

提问于
浏览
0
# -*- 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)

python3 defult编码不是'UTF-8'吗?

当我运行这个脚本

它实际上是python3.5.2

当我打印出身体的类型时,它是str

但错误似乎是asciicode而不是python2的unicode

谢谢

1 回答

  • 2

    smtplib.SMTP.sendmail expects its msg argument to be a str 仅包含ascii字符或 bytes

    msg可以是包含ASCII范围内字符的字符串,也可以是字节字符串 . 使用ascii编解码器将字符串编码为字节,并将单个\ r和\ n字符转换为\ r \ n字符 . 不修改字节字符串 .

    您的邮件是一个字符串,但包含非ascii字符;你需要编码为字节:

    smtpObj.sendmail(from_add, to, email_text.encode('utf-8'))

相关问题