【问题标题】:UnicodeDecodeError when try to send simple letter using smtp尝试使用 smtp 发送简单字母时出现 UnicodeDecodeError
【发布时间】:2018-11-24 17:09:42
【问题描述】:

我在使用 smtplib 发送简单信件时遇到问题。我的程序在这一行停止smtplib.SMTP('smtp.gmail.com', port=587) 错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 7: invalid continuation byte。我该如何解决这个问题?

文件编码:UTF-8(所有符号均为英文)

Python 版本:3.6.4

完整程序:

import smtplib
from email.message import EmailMessage

mail_addr = "myemail@gmail.com"

msg = EmailMessage()
msg['From'] = mail_addr
msg['To'] = "myemail@gmail.com"
msg['Subject'] = "Hello!"
msg.set_content('Email body')

email_address = "myemail@gmail.com"
email_password = "password"

body = "Hello, world!"

server = smtplib.SMTP('smtp.gmail.com', port=587)
server.ehlo()
server.starttls()
server.login(email_address, email_password)
server.send_message(msg=msg, from_addr=mail_addr, to_addrs=mail_addr)

print('Email sent successfully')

完整输出:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydev_run_in_console.py", line 53, in run_file
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/MyPrograms/Python/docsCreator/main/starter.py", line 21, in <module>
    server = smtplib.SMTP('smtp.gmail.com', port=587)
  File "C:\Users\Dmitry\AppData\Local\Programs\Python\Python36-32\Lib\smtplib.py", line 261, in __init__
    fqdn = socket.getfqdn()
  File "C:\Users\Dmitry\AppData\Local\Programs\Python\Python36-32\Lib\socket.py", line 673, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 7: invalid continuation byte
PyDev console: starting.

【问题讨论】:

    标签: python python-3.x utf-8 smtp smtplib


    【解决方案1】:

    问题可能出在您的主机名上吗? 来自socket.py

    def getfqdn(name=''):
        name = name.strip()
        if not name or name == '0.0.0.0':
            name = gethostname()
        try:
            hostname, aliases, ipaddrs = gethostbyaddr(name)
        except error:
            pass
    ...
    

    socket.gethostname() 的输出是什么?

    【讨论】:

    • socket.gethostname() 包含西里尔符号,我重命名计算机名称,一切都开始工作了。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2014-05-16
    • 2016-08-12
    • 2011-08-31
    • 1970-01-01
    • 2018-09-09
    • 2014-03-11
    相关资源
    最近更新 更多