Search code examples
pythonwindowsemailsmtpsmtplib

SMTP.starttls() TimeoutError on Windows 10


Today I have tried to send email with python:

import smtplib

EMAIL_HOST = 'smtp.google.com'
EMAIL_PORT = 587

EMAIL_FROM_LOGIN = 'sender@gmail.com'
EMAIL_FROM_PASSWORD = 'password'

MESSAGE = 'Hi!'

EMAIL_TO_LOGIN = 'recipient@gmail.com'

print('starting...')
server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
server.starttls()

print('logging...')
server.login(EMAIL_FROM_LOGIN, EMAIL_FROM_PASSWORD)

print('sending message...')
server.sendmail(EMAIL_FROM_LOGIN, EMAIL_TO_LOGIN, MESSAGE)

This script doesn't goes further than starting... print. I searched about this issue whole day, but found only something like:

"check that port isn't blocked..."

At least I got info about blocked/disabled/etc. port, what I don't have, is specifics of problem.


Additional info: following some of advices I found earlier, I checked output of telnet smtp.google.com 587. The output is static Connecting to smtp.google.com.... It remains for like 2 mins, and then prints:

Could not open a connection to this host, on port 587: Connection failed


UPD 1

I tried to open ports manually, on which python script has been run, but nothing changes...


So, my question is: what should I do? Where I can find those blocked ports, how to unblock/enable them?


Solution

  • Enable lower security in your gmail account and fix your smtp address: 'smtp.gmail.com':

    My sample:

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    mail_content = 'Sample text'
    
    sender_address = 'xxx@xxx'
    sender_pass = 'xxxx'
    receiver_address = 'xxx@xxx'
    
    message = MIMEMultipart()
    message['From'] = sender_address
    message['To'] = receiver_address
    message['Subject'] = 'Test mail'
    message.attach(MIMEText(mail_content, 'plain'))
    
    session = smtplib.SMTP('smtp.gmail.com', 587)
    session.starttls()
    session.login(sender_address, sender_pass)
    session.sendmail(sender_address, receiver_address, message.as_string())
    session.quit()
    
    print('Mail Sent')