Python freezes on smtplib.SMTP("smtp.gmail.com", 587)

It is most likely a firewall or similar issue. On the machine having the issue, try running this on the command line:

ping smtp.gmail.com

Assuming that works, then try:

telnet smtp.gmail.com 587

I'm assuming a Linux machine with this command. You'll need to adapt for others. If that connects, type ehlo list and the command should show some info. Type quit to exit.

If that doesn't work, then check your iptables.

sudo iptables -L

This will either show something like ACCEPT all under Chain INPUT or if not, you'll need to ensure that you are accepting established connections with something like:

ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED

The output chain is often open, but you should check that too.

If you are on AWS, check your security group isn't blocking outgoing connections.


Use server.ehlo() in your code.

Code Snippet:

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()

For authentication error: http://joequery.me/guides/python-smtp-authenticationerror/

Add following code snippet and run again.

try:
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, msg)
    server.close()
    print 'successfully sent the mail'
except:
    print "failed to send mail"

Tags:

Python

Smtplib