Forums

OSError: [Errno 101] Network is unreachable

Hi,

I am having the getting the following error when trying to send a message through gmail with my app.

OSError: [Errno 101] Network is unreachable

I am not too sure what the error is about, I did have a look on the forums and apparently free users might not be able to send emails due to problems with spamming in the past.

Is there anyway I can get my emails to be allowed through or is the only option to pay for any account.

I am beginner when it comes to this sort of thing but I imagine it is trying to send out my confirmation email to the user upon signing up but for some reasons this is failing.

Here is the full error trace:

2020-05-19 17:51:07,130: Exception on /register [POST]
Traceback (most recent call last):
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 1951, in 
full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 1820, in 
handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 1949, in 
full_dispatch_request
rv = self.dispatch_request()
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 1935, in 
dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "./flaskmovie/routes.py", line 41, in register
user.confirmation_email()
File "./flaskmovie/models.py", line 89, in confirmation_email
mail.send(message)
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask_mail.py", line 491, in send
with self.connect() as connection:
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask_mail.py", line 144, in __enter__
self.host = self.configure_host()
File "/home/teetwofour/.virtualenvs/env/lib/python3.7/site-packages/flask_mail.py", line 158, in configure_host
host = smtplib.SMTP(self.mail.server, self.mail.port)
File "/usr/lib/python3.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.7/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.7/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/lib/python3.7/socket.py", line 727, in create_connection
raise err
File "/usr/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
OSError: [Errno 101] Network is unreachable

Can someone please help me find a way to solve this!

Thank you.

-teetwofour

SMTP using GMail should work -- we have an exception for their servers, as we figure that they are very much capable of handling any anti-spam measures. What specific email server is your code configured to use?

Hi I am using this flask_mail along with:

app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True

what is interesting is that I tested this morning and it seemed to work fine?!?!?

No idea why but it does seem to be working now, hopefully it continues this way otherwise I may end up looking into one of the services such as sendgrid recommended here.

Thanks!

It looks like Google have changed the IPs involved and the way that we were using to find the IPs before does not seem to work any more. We are trying to work out what the new way is to get the appropriate IPs and provide the exceptions that are necessary to make it work.

Ok. We've added the new IP range to the rules so it should work now.

Hello, my name is Tharlles, I have a django application in a free account. I need to generate a pdf file with my model data and I get the same error! [Errno 101] Network is unreachable

What host are you trying to connect to with your PDF-generation code, and what code are you using to do it?

Hello, I'm using Pisa from the library xhtml2pdf!

This is the View responsible:

from xhtml2pdf import pisa 
       def render_pdf_view(request):
            hoje = date.today()
            pdfs = hoje.strftime('%d/%m/%Y')
            dias = ('Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado', 'Domingo')
            hj = dias[hoje.weekday()]
            hora_agora = datetime.now()
            hora = hora_agora.strftime('%H:%M')
            acertivos = Escolha.objects.filter(sorteado=True).count()
            pessoa = Pessoa.objects.all()

            template_path = 'pdf_template/invoice.html'
            context = {
                'hj':hj,
                'hora':hora,
                'hoje':hoje,
                'pessoa': pessoa,
                'acertivos':acertivos,
            }
            # Create a Django response object, and specify content_type as pdf
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="http://tharlleste.pythonanywhere.com/static/pdfs/{}.pdf"'.format(pdfs)
            # find the template and render it.
            template = get_template(template_path)
            html = template.render(context)

            # create a pdf
            pisa_status = pisa.CreatePDF(
               html, dest=response )
            # if error then show some funy view
            if pisa_status.err:
               return HttpResponse('We had some errors <pre>' + html + '</pre>')
            return response

The HTML that you are converting to a PDF is accessing resources from places that are not on the whitelist, so the conversion fails. It's unlikely that the places serving those resources are candidates for he whitelist, so I would suggest downloading the resources on your local machine, uploading them to your PythonAnywhere account and then use local file URLS to access them in the HTML that you are using for the PDF.

Hi Team

i am trying to send email with attachment using senditblue api, Code works fine from local machine. It gives error when triggered from pythonanywhere Task.

            code sample below :

            configuration = sib_api_v3_sdk.Configuration()
            configuration.api_key['api-key'] = 'API Key'

            api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
            subject = "This weeks Volume Scanner"
            html_content = "<html><body><h1>Find attached weekly volume breakout scripts</h1></body></html>"
            sender = {"name":"Rutvij","email":"myemail@gmail.com"}
            to = [{"email":"abc@gmail.com","name":"abc"},{"email":"pqr@gmail.com","name":"pqr"}]
            reply_to = {"email":"myemail@gmail.com","name":"my email"}
            headers = {"Some-Custom-Name":"unique-id-1234"}

            THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
            filename = os.path.join(THIS_FOLDER,'HigherTradeQuantityThisWeek.csv')
            data = open(filename, "r").read().encode('utf-8')
            attachment = [{"content":base64.b64encode(data).decode('utf-8'), "name":"HigherTradeQuantityThisWeek.csv"}]
            send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=to,reply_to=reply_to, headers=headers, html_content=html_content, sender=sender, subject=subject,attachment=attachment)

            try:
                api_response = api_instance.send_transac_email(send_smtp_email)
                pprint(api_response)
            except ApiException as e:
                print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)


            Error details below :

            2021-10-23 06:40:29,564 WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f947f768940>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /v3/smtp/email
            2021-10-23 06:40:31,612 WARNING Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f947f768d60>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /v3/smtp/email
            2021-10-23 06:40:33,660 WARNING Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f947f768ee0>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /v3/smtp/email
            Traceback (most recent call last):
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connection.py", line 169, in _new_conn
                conn = connection.create_connection(
              File "/usr/local/lib/python3.8/dist-packages/urllib3/util/connection.py", line 96, in create_connection
                raise err
              File "/usr/local/lib/python3.8/dist-packages/urllib3/util/connection.py", line 86, in create_connection
                sock.connect(sa)
            OSError: [Errno 101] Network is unreachable

            During handling of the above exception, another exception occurred:

            Traceback (most recent call last):
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 699, in urlopen
                httplib_response = self._make_request(
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 382, in _make_request
                self._validate_conn(conn)
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 1010, in _validate_conn
                conn.connect()
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connection.py", line 353, in connect
                conn = self._new_conn()
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connection.py", line 181, in _new_conn
                raise NewConnectionError(
            urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f947f7490a0>: Failed to establish a new connection: [Errno 101] Network is unreachable

            During handling of the above exception, another exception occurred:

            Traceback (most recent call last):
              File "/home/rutvij/VolumeScanner/WeeklyVolumeScanner.py", line 312, in <module>
                EmailFile()
              File "/home/rutvij/VolumeScanner/WeeklyVolumeScanner.py", line 296, in EmailFile
                api_response = api_instance.send_transac_email(send_smtp_email)
              File "/home/rutvij/.local/lib/python3.8/site-packages/sib_api_v3_sdk/api/transactional_emails_api.py", line 1735, in send_transac_email
                (data) = self.send_transac_email_with_http_info(send_smtp_email, **kwargs)  # noqa: E501
              File "/home/rutvij/.local/lib/python3.8/site-packages/sib_api_v3_sdk/api/transactional_emails_api.py", line 1798, in send_transac_email_with_http_info
                return self.api_client.call_api(
              File "/home/rutvij/.local/lib/python3.8/site-packages/sib_api_v3_sdk/api_client.py", line 329, in call_api
                return self.__call_api(resource_path, method,
              File "/home/rutvij/.local/lib/python3.8/site-packages/sib_api_v3_sdk/api_client.py", line 161, in __call_api
                response_data = self.request(
              File "/home/rutvij/.local/lib/python3.8/site-packages/sib_api_v3_sdk/api_client.py", line 371, in request
                return self.rest_client.POST(url,
              File "/home/rutvij/.local/lib/python3.8/site-packages/sib_api_v3_sdk/rest.py", line 269, in POST
                return self.request("POST", url,
              File "/home/rutvij/.local/lib/python3.8/site-packages/sib_api_v3_sdk/rest.py", line 162, in request
                r = self.pool_manager.request(
              File "/usr/local/lib/python3.8/dist-packages/urllib3/request.py", line 78, in request
                return self.request_encode_body(
              File "/usr/local/lib/python3.8/dist-packages/urllib3/request.py", line 170, in request_encode_body
                return self.urlopen(method, url, **extra_kw)
              File "/usr/local/lib/python3.8/dist-packages/urllib3/poolmanager.py", line 375, in urlopen
                response = conn.urlopen(method, u.request_uri, **kw)
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 783, in urlopen
                return self.urlopen(
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 783, in urlopen
                return self.urlopen(
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 783, in urlopen
                return self.urlopen(
              File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 755, in urlopen
                retries = retries.increment(
              File "/usr/local/lib/python3.8/dist-packages/urllib3/util/retry.py", line 573, in increment
                raise MaxRetryError(_pool, url, error or ResponseError(cause))
            urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.sendinblue.com', port=443): Max retries exceeded with url: /v3/smtp/email (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f947f7490a0>: Failed to establish a new connection: [Errno 101] Network is unreachable'))

            2021-10-23 06:40:36 -- Completed task, took 28.88 seconds, return code was 1.

api.sendinblue.com is whitelisted so maybe the package you use to connect is not respecting proxy settings. See https://help.pythonanywhere.com/pages/403ForbiddenError/

OSError: [Errno 101] Network is unreachable I am getting the flowing error when trying to send otp on mobile number with my app. its work fine on local host , but when i have hosted on pythonanywhere i got the error.

code simple below:

def send_otp(mobile, otp): conn = http.client.HTTPConnection("2factor.in") authkey = api_key_sms phone = mobile otp = otp otp_template = 'LoginOtp' payload = "" headers = {'content-type': "application/x-www-form-urlencoded"} conn.request("GET", f"/API/V1/{authkey}/SMS/{phone}/{otp}/{otp_template}", payload, headers) res = conn.getresponse() data = res.read()

print(data.decode("utf-8"))
return None

errrors :

        Traceback (most recent call last):
        File "/home/anilkumar/djcommerce/my_env/lib/python3.8/site-packages/django/core/handlers                       /exception.py", line 47, in inner
        response = get_response(request)
        File "/home/anilkumar/djcommerce/my_env/lib/python3.8/site-packages/django/core/handlers/base.py",
       line 181, in _get_response
         response = wrapped_callback(request, *callback_args, **callback_kwargs)
        File "/home/anilkumar/djcommerce/core/views.py", line 56, in register
        send_otp(mobile, otp)
        File "/home/anilkumar/djcommerce/core/views.py", line 35, in send_otp
        conn.request("GET", f"/API/V1/{authkey}/SMS/{phone}/{otp}/{otp_template}", payload, headers)
        File "/usr/lib/python3.8/http/client.py", line 1230, in request
        self._send_request(method, url, body, headers, encode_chunked)
       File "/usr/lib/python3.8/http/client.py", line 1276, in _send_request
      self.endheaders(body, encode_chunked=encode_chunked)
     File "/usr/lib/python3.8/http/client.py", line 1225, in endheaders
     self._send_output(message_body, encode_chunked=encode_chunked)
     File "/usr/lib/python3.8/http/client.py", line 1004, in _send_output
     self.send(msg)
     File "/usr/lib/python3.8/http/client.py", line 944, in send
    self.connect()
    File "/usr/lib/python3.8/http/client.py", line 915, in connect
    self.sock = self._create_connection(
    File "/usr/lib/python3.8/socket.py", line 807, in create_connection
    raise err
    File "/usr/lib/python3.8/socket.py", line 796, in create_connection
    sock.connect(sa)

    Exception Type: OSError at /register/
    Exception Value: [Errno 101] Network is unreachable

What is the full traceback message of your error?

Hello. I am trying to send a mail using outlook api through pythonanywhere.com, but I too am getting the same "[Error 101] Network is unreachable". Please how do I resolve this. Thanks. Below is the full traceback message of the error.

[shortened by admin]

2022-03-31 08:24:43,639: Internal Server Error: /
Traceback (most recent call last):
  File "/home/n3utron/.virtualenvs/bdayappvenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/n3utron/.virtualenvs/bdayappvenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/n3utron/mitc_bdayapp/sendmail/sendmail/views.py", line 54, in bdaycheck
    return sendmail(celebrants, request)
  File "/home/n3utron/mitc_bdayapp/sendmail/sendmail/views.py", line 59, in sendmail
    connection.open()
  File "/home/n3utron/.virtualenvs/bdayappvenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 80, in open
    self.connection = self.connection_class(
  File "/usr/local/lib/python3.9/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/local/lib/python3.9/smtplib.py", line 341, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/local/lib/python3.9/smtplib.py", line 312, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/local/lib/python3.9/socket.py", line 843, in create_connection
    raise err
  File "/usr/local/lib/python3.9/socket.py", line 831, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable

I shortened the message to the traceback of the last error (no need in pasting full error log). Regaring the issue -- free accounts can use only HTTP email services, the only supported SMTP on free accounts is Gmail's, see this help page.

Hello. Please, add this url to whitelist: api.telegram.org:443. This url is used by telegram bots to interact with the telegram bot API. The error I get is as follows.

aiogram.utils.exceptions.NetworkError: Aiohttp client throws an error: ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]

That is already on the whitelist. You need to configure your client to connect through the proxy. See the documentation for the library you're using for how to do that and https://help.pythonanywhere.com/pages/403ForbiddenError/ for the proxy details that you need to use.

Hello. I am trying to send an email via yandex.ru but I get an error.

smtplib.SMTP_SSL('smtp.yandex.ru', 465)

Error:

Traceback (most recent call last):
 File "/home/Internet1Soft/trade_bot/indicators/indicator sma/moving_avarage.py", line 
 233, in <module>
 loop_start(main_path_server)
 File "/home/Internet1Soft/trade_bot/indicators/indicator sma/moving_avarage.py", line 
214, in loop_start
sending_by_mail(list_trends)
File "/home/Internet1Soft/trade_bot/indicators/indicator sma/moving_avarage.py", line 
174, in sending_by_mail
server = smtplib.SMTP_SSL('smtp.yandex.ru', 465)  # Создаем объект SMTP
File "/usr/local/lib/python3.9/smtplib.py", line 1045, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout,
File "/usr/local/lib/python3.9/smtplib.py", line 255, in __init__
(code, msg) = self.connect(host, port)
File "/usr/local/lib/python3.9/smtplib.py", line 341, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python3.9/smtplib.py", line 1051, in _get_socket
new_socket = super()._get_socket(host, port, timeout)
File "/usr/local/lib/python3.9/smtplib.py", line 312, in _get_socket
return socket.create_connection((host, port), timeout,
 File "/usr/local/lib/python3.9/socket.py", line 843, in create_connection
raise err
File "/usr/local/lib/python3.9/socket.py", line 831, in create_connection
sock.connect(sa)
  OSError: [Errno 101] Network is unreachable

Free accounts cannot use SMTP except through gmail: https://help.pythonanywhere.com/pages/SMTPForFreeUsers/

last post was very helpful

Glad to hear that!