I am learning python smtlib ,i am trying to send mail using SMTP . when i run i'm getting :An error occurred: [Errno 60] Operation timed out

56 views Asked by At

I am trying to send Mail using python smtplib. My code is as follows:

import smtplib


email = "[email protected]"  # Set your email as an environment variable
password_email = "XXXX XXXX XXXX XXXX"  # Used google app password 

if not email or not password_email:
    print("Please set your email and password as environment variables.")
    exit()

sender_email = "gXXXXXXXXX^[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hello from Python

This is a test email sent from Python.
"""

try:
    with smtplib.SMTP("smtp.gmail.com") as connection:
        connection.starttls()
        connection.login(user=email, password=password_email)
        connection.sendmail(from_addr=sender_email, to_addrs=receiver_email, msg=message)
    print("Email sent successfully.")
except Exception as e:
    print(f"An error occurred: {e}")

When I run this program nothing is happening in the terminal. After a few minutes I am receiving the following error: An error occurred: [Errno 60] Operation timed out

Where am I going wrong?

I tried in latest version of VS code and the latest Python version. I am using VS Code in MACBOOK AIR M1.

I am expecting to send a mail through Python between two Gmail addresses.

2

There are 2 answers

1
prohit On

If you're using Gmail as the provider, you'll need to tell Google to allow you to connect via SMTP, which is considered a "less secure" method. This option can be found in your Google account settings (for the sender email). For reference: https://support.google.com/accounts/answer/6010255

0
Muhammed Samed Özmen On

email = "[email protected]" sender_email = "gXXXXXXXXX^[email protected]"

if they are not the same that's why you getting an error. Your logged main and sender mail are different. So, you can get an error because of that. Instead of that use that.

    connection.sendmail(from_addr=email, to_addrs=receiver_email, msg=message) 
    connection.close()