Forums

OSError: [Errno 101] Network is unreachable

I'm getting the following error when trying to send an email through outlook using smpt.office365.com:

Traceback (most recent call last):
  File "/home/anwg01/auto_bday_alerts/main.py", line 151, in <module>
    main()
  File "/home/anwg01/auto_bday_alerts/main.py", line 147, in main
    send_email(day_alert_msg)   # send email
  File "/home/anwg01/auto_bday_alerts/main.py", line 114, in send_email
    with smtplib.SMTP(servers["outlook"], port=587) as connection:
  File "/usr/local/lib/python3.10/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/local/lib/python3.10/smtplib.py", line 341, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/local/lib/python3.10/smtplib.py", line 312, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/local/lib/python3.10/socket.py", line 845, in create_connection
    raise err
  File "/usr/local/lib/python3.10/socket.py", line 833, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable

My program works fine when running locally and emails are sent but not in pythonanywhere for some reason. The other odd thing is that my program ran the first time but now everytime I run it, I get this "OSError: [Errno 101] Network is unreachable" error.

I am using:

with smtplib.SMTP("smtp.office365.com", port=587) as connection:
        connection.starttls()   # ensures encryption and prevents data interception
        connection.login(
            user=from_email,
            password=app_password
        )

[edit by admin: formatting]

Free accounts on PythonAnywhere have restricted Internet access -- you can only make outbound HTTP/HTTPS requests to sites on our allowlist, and you can only make SMTP requests to Gmail's SMTP servers.

Thank you for the information. Would you know why my program was successful the very first time? Was this a fluke?

It'd be impossible for us to say without know what your code was doing