OSError [Errno 101] Network is unreachable, when trying to send Email in Django using smtplib on GoDaady Server

Hi there, I have a strange issue. I have a Payment app in Django, deployed on GoDaddy. In app, I need to send email to the user when their payment is successful. I am using smtplib and email libraries. The steps I did are:

  • Created Application Password in Google Account
  • Used my email, that app password, 587 port and smtp.gmail.com server

The problem is, it totally works fine on my local host and I receive the email. But, it is not working on GoDaddy and I receive the following error:

[Errno 101] Network is unreachable
Traceback (most recent call last):
  File "/home/g549hesohwxf/public_html/pl_payment_gateway/app/utils.py", line 52, in send_email
    with smtplib.SMTP(smtp_server, smtp_port) as server:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/alt/python311/lib64/python3.11/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
                  ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/alt/python311/lib64/python3.11/smtplib.py", line 341, in connect
    self.sock = self._get_socket(host, port, self.timeout)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/alt/python311/lib64/python3.11/smtplib.py", line 312, in _get_socket
    return socket.create_connection((host, port), timeout,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/alt/python311/lib64/python3.11/socket.py", line 851, in create_connection
    raise exceptions[0]
  File "/opt/alt/python311/lib64/python3.11/socket.py", line 836, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable

I searched around the web and got to know that many hosts block this ports by default to avoid spamming. I tried talking to GoDaddy support. They said following things:

  • GoDaddy does not block this port
  • Use the Microsoft Office 365 SMTP Server details.

I used their own details which is smtp.office365.com, 587 port and the email which I created on my domain in GoDaddy. But, I still see the same error. I reported this issue to GoDaddy and they said, they can’t help, the issue is in my app. I can’t figure out the issue as it works perfectly fine on my local host. More strange thing is, the SMTP details are of the same account which I am using in GoDaddy provided Email Account and the email account works fine and I can send the email through that, it’s just my Django app which is not able to send emails using that same account details.

Below is my email sending code:

import logging

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


logger = logging.getLogger()

def send_email(response_status_code, response_dict, order_details):
    logger.info("SETTING UP SMTP SERVER...")
        
    smtp_server = 'smtp.office365.com'
    smtp_port = 587
    smtp_username = 'no-reply@parkinglink.com.au'
    smtp_password = [hidden-password]
    sender_email = 'no-reply@parkinglink.com.au'
    receiver_email = order_details['email']
    
    logger.info("SETTING EMAIL DETAILS...")
    
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = 'New Booking Creation Status | ParkingLink'
    
    booking_status = "NOT created"
    
    if int(response_status_code) == 200 and str(response_dict["success"]).lower() == "true":
        booking_status = "created successfully"
        
    logger.info("WRITING EMAIL BODY...")
    
    email_body = f"""
    Dear User,
    
    Your booking was {booking_status}.
    
    Regards,
    ParkingLink
    """
    
    logger.info("EMAIL BODY: %s", email_body) # CODE WORKS FINE UP TO THIS STEP
    
    msg.attach(MIMEText(email_body, 'plain'))
    
    try:
        logger.info("CONNECTING TO SMTP SERVER...")
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            logger.info("STARTING TLS...")
            server.starttls()  # Secure the connection
            logger.info("LOGGING INTO EMAIL CLIENT...")
            server.login(smtp_username, smtp_password) 
            logger.info("CREATING NEW EMAIL...")
            text = msg.as_string()
            logger.info("SENDING EMAIL...")
            server.sendmail(sender_email, receiver_email, text) 
        logger.info("EMAIL SENT SUCCESSFULLY!")
    except Exception as e:
        logger.info("Failed to send email: %s", e, exc_info=True)

Can anyone help me in this?

try to do:

$ telnet smtp.office365.com 587 # just to check if you can reached it 

you might need to allow this outbound connection in your firewall: (assuming it is a Linux VPS, nothing fancy)

$ sudo ufw allow out 587
# if that didn't solve it, screenshot the status result? maybe we'll find something there  
$ sudo ufw status verbose

@wassef911 where do I need to run the telnet command? In GoDaddy’s terminal? Also do I need to run sudo ufw allow out 587 in GoDaddy?

Hi, the solution that worked for me is:

All you need to do is add the code below to settings.py:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25

Then, inside the file where you are trying to send an email, use the EmailMessage class for sending the email.

Best regards,

@wassef911 getting these errors:

@mghiasvandm can you share your email sending code which worked for you? I tried your suggestion but it did not work for me.

Can anyone help me out??

Still could not solve my issue.