I can't solve the problem of sending an email in any way with gmail.com , neither with mail.ru(bk.ru): when creating SMTP, even empty, this error occurs I use 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() # Выходим
If I replace
server = smtplib.SMTP_SSL('smtp.mail.ru', 465)
with
server = smtplib.SMTP_SSL()
server.connect('smtp.mail.ru', 465)
and even without _SSL(but it no connection on the server), then this error still comes out at the stage 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
I understand the meaning of the error, but it looks like it's somewhere inside the smtplib itself - and this puts me in a confusion
The library tries to use socket.getfqdn()
to find out the local host name to send to the remote server:
...
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
...
So the question is: what is your hostname? The problem might be that it contains non-ascii characters and fails to be decoded as UTF-8.
One possible solution, besides changing the hostname, would be to explicitly pass the local_hostname
in the constructor:
server = smtplib.SMTP_SSL('smtp.mail.ru', 465, 'your.host.name')