Search code examples
pythonsmtplib

Getting "Network is unreachable" for python smtplib


I've tried to set up email confirmation for django app, and after a few failure steps I tried it with simple python module using smtplib (going through Corey's tutorial) but after the first part of tutorial when he got the email I got this error after about 30 seconds of waiting:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    with smtplib.SMTP('smtp.gmail.com', port) as smtp:
  File "/usr/lib/python3.8/smtplib.py", line 253, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python3.8/smtplib.py", line 339, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python3.8/smtplib.py", line 308, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/lib/python3.8/socket.py", line 808, in create_connection
    raise err
  File "/usr/lib/python3.8/socket.py", line 796, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable

This is the code

with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()

        smtp.login(username, password)

        subject = 'Test'
        body = 'Testing smtp library'

        msg = f'Subject: {subject}\n\n{body}'
        smtp.sendmail(username, username, msg)

I'm using 2-factor authentication and app password, and I've checked the 16 digit password, However I don't know other ways to check if I'm able to sign in with these credentials.


Solution

  • The problem was that I was using a VPN (I don't know why because I'm logged in from VPN's location), However I got another problem and couldn't log in after that and got another error

    Traceback (most recent call last):
      File "main.py", line 12, in <module>
        smtp.login(username, username)
      File "/usr/lib/python3.8/smtplib.py", line 734, in login
        raise last_exception
      File "/usr/lib/python3.8/smtplib.py", line 723, in login
        (code, resp) = self.auth(
      File "/usr/lib/python3.8/smtplib.py", line 646, in auth
        raise SMTPAuthenticationError(code, resp)
    smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials k18sm34466285edx.18 - gsmtp')
    

    So I just tried another option. I used yagmail and it's just fine with the same credentials that I was using. So I guess the problem was that smtplib wasn't accepted from gmail.