如何在python3 sendmail中修复'UnicodeEncodeError'

时间:2019-08-19 04:20:52

标签: python python-3.x smtp sendmail

我想使用python发送电子邮件。 但是我收到以下错误:

Traceback (most recent call last):
  File "mail.py", line 26, in <module>
    to_mail()
  File "mail.py", line 22, in to_mail
    smtp.sendmail(from_address, to_address, msg.as_string())
  File "/home/centos/.pyenv/versions/3.7.1/lib/python3.7/smtplib.py", line 861, in sendmail
    (code, resp) = self.mail(from_addr, esmtp_opts)
  File "/home/centos/.pyenv/versions/3.7.1/lib/python3.7/smtplib.py", line 534, in mail
    self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
  File "/home/centos/.pyenv/versions/3.7.1/lib/python3.7/smtplib.py", line 367, in putcmd
    self.send(str)
  File "/home/centos/.pyenv/versions/3.7.1/lib/python3.7/smtplib.py", line 352, in send
    s = s.encode(self.command_encoding)
UnicodeEncodeError: 'ascii' codec can't encode character '\uff20' in position 15: ordinal not in range(128)

这是我使用的环境。

  • centos7
  • Python 3.7.1
  • print(sys.stdout.encoding)-> UTF8

我的代码是这个。

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formatdate
from email import charset


from_address = 'from@xxxxx.jp'
to_address = 'haruraruru@xxxx.jp'

subject = "ERROR"
text = "check error.log"

msg = MIMEText(text,'Plane')
msg['Subject'] = Header(subject)
msg['From'] = from_address
msg['To'] = to_address

def to_mail():
    smtp = smtplib.SMTP('localhost')
    smtp.sendmail(from_address, to_address, msg.as_string())
    smtp.quit()

to_mail()

我该怎么做才能通过python向我发送电子邮件?

1 个答案:

答案 0 :(得分:1)

@变量的from_address符号中,它看起来像是非标准字符。 您可能会复制并粘贴它吗?

尝试将其更改为标准@,看看它是否可以编码