Search code examples
pythonsmtplibconnection-timeout

Getting timeout error while using smtplib library to send email


Here is my code:

import smtplib

connection = smtplib.SMTP("smtp.gmail.com")
connection.starttls()
connection.login(user="mymail@gmail.com", password="mypassowrd")
connection.sendmail(from_addr="mymail@gmail.com", to_addrs="recievermail@gmail.com", msg="Hello")
connection.close()

So I am getting this error:

Traceback (most recent call last):
  File "E:\100Days-Python_programs\Day32\Birthday Wisher (Day 32) start\main.py", line 3, in <module>
    connection = smtplib.SMTP("smtp.gmail.com")
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 253, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 339, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 310, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\socket.py", line 843, in create_connection
    raise err
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\socket.py", line 831, in create_connection
    sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Process finished with exit code 1

I turned on Less secure app access: enter image description here

I turned off every security steps too: enter image description here

And I also turned off the firewall protection as well.

But Nothing worked.

So please someone help me.


Solution

  • You need to specify the port. In this case, it's 587 for TSL.

    Somehow it works, but I don't have profound knowledge to explain why.

    I had the same problem, so there is a solution:

    connection = smtplib.SMTP("smtp.gmail.com", 587)