Search code examples
pythonpython-3.xutf-8smtpsmtplib

UnicodeDecodeError when try to send simple letter using smtp


I have a problem with sending simple letter using smtplib. My program downing at this line smtplib.SMTP('smtp.gmail.com', port=587) with error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 7: invalid continuation byte. How can I resolve this problem?

File encoding: UTF-8 (all symbols are English)

Python version: 3.6.4

Full program:

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')

Full output:

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.

Solution

  • Can the problem be in your hostname? From 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
    ...
    

    What is the output of socket.gethostname()?