Python 创建 smtp() 时出现 smtplib 错误:'utf-8' 编解码器无法解码字节

Python smtplib error when creating smtp(): 'utf-8' codec can't decode byte

我无法通过 gmail.com 以任何方式解决发送电子邮件的问题,也无法通过 mail.ru(bk.ru) 解决:创建 SMTP 时,即使为空,也会出现此错误发生 我用 PyCharm 2020.1

import requests
import smtplib                                      # Импортируем библиотеку по работе с SMTP

from email.mime.multipart import MIMEMultipart      # Многокомпонентный объект
from email.mime.text import MIMEText                # Текст/HTML
from email.mime.image import MIMEImage              # Изображения

addr_from = "zabrell@bk.ru"                 # Адресат
addr_to   = "zabrell@bk.ru"                   # Получатель
password  = "***"                                  # Пароль

msg = MIMEMultipart()                               # Создаем сообщение
msg['From']    = addr_from                          # Адресат
msg['To']      = addr_to                            # Получатель
msg['Subject'] = '1'                   # Тема сообщения
body = '1'
msg.attach(MIMEText(body, 'plain'))                 # Добавляем в сообщение текст

server = smtplib.SMTP_SSL('smtp.mail.ru', 465)      # Создаем объект SMTP
server.login(addr_from, password)                   # Получаем доступ
server.send_message(msg)                            # Отправляем сообщение
server.quit()                                       # Выходим

如果我替换

server = smtplib.SMTP_SSL('smtp.mail.ru', 465)

server = smtplib.SMTP_SSL() 
server.connect('smtp.mail.ru', 465)

即使没有_SSL(但它在服务器上没有连接),那么这个错误仍然出现在smtplib.SMTP_SSL()

阶段
Traceback (most recent call last):
  File "C:/Users/zabre/PycharmProjects/miners_test/script.py", line 35, in <module>
    server = smtplib.SMTP_SSL('smtp.mail.ru', 465)      # Создаем объект SMTP
  File "C:\Users\zabre\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 1034, in __init__
    SMTP.__init__(self, host, port, local_hostname, timeout,
  File "C:\Users\zabre\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 263, in __init__
    fqdn = socket.getfqdn()
  File "C:\Users\zabre\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 756, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf7 in position 10: invalid start byte

Process finished with exit code 1

我理解错误的含义,但它看起来像是在 smtplib 本身的某个地方 - 这让我感到困惑

库尝试使用 socket.getfqdn() 找出要发送到远程服务器的本地主机名:

...
    if local_hostname is not None:
        self.local_hostname = local_hostname
    else:
        # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and
        # if that can't be calculated, that we should use a domain literal
        # instead (essentially an encoded IP address like [A.B.C.D]).
        fqdn = socket.getfqdn()
        if '.' in fqdn:
            self.local_hostname = fqdn
...

所以问题是:您的主机名是什么?问题可能是它包含非 ascii 字符并且无法解码为 UTF-8。

除了更改主机名之外,一个可能的解决方案是在构造函数中显式传递 local_hostname

server = smtplib.SMTP_SSL('smtp.mail.ru', 465, 'your.host.name')