Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

smtplib

I am attempting to create a script that send an email, using Gmail. However, my code freezes when the line below is ran:

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

It is before my username and password are entered, so it is nothing to do with my Gmail account. Why is this happening? I am using Python 3.6.3

The full code is below:

import smtplib

# Specifying the from and to addresses

fromaddr = '[email protected]'
toaddrs  = '[email protected]'

# Writing the message (this message will appear in the email)

msg = 'Enter you message here'

# Gmail Login

username = '[email protected]'
password = 'PPP'

# Sending the mail  

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
like image 217
OD1995 Avatar asked May 31 '18 12:05

OD1995


3 Answers

If it's hanging in the call to smtplib.SMTP, and the server requires SSL, then most likely the issue is that you need to call smtplib.SMTP_SSL() (note the _SSL) instead of calling smtplib.SMTP() with a subsequent call to server.starttls() after the ehlo. See SMTPLib docs for SMTP_SSL for more details.

This fixed the issue for me.

like image 60
Chris Kline Avatar answered Nov 15 '22 16:11

Chris Kline


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"
like image 26
Ajay Shewale Avatar answered Nov 15 '22 15:11

Ajay Shewale


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.

like image 6
Phil Avatar answered Nov 15 '22 15:11

Phil