How to send emails from a python script using Gmail’s SMTP servers

Hello people,

I decided to write down all the steps involved since this topic seems to be quite popular and many people have issues about that, especially when using GMail.

First, the software requirements:

  • Python 2.7 + (which comes with smtplib)

For smtplib to work, you need to have SSL and all its accompanying packages installed. I use Fedora. Therefore, go ahead and install openssl-devel:

sudo yum install -y openssl-devel

If you are going to use a python script to send an email, you will need to tweak your Gmail (Google) security settings because my default Google blocks any unsecure 3rd-party applications accessing your account. This is great for security but not good for our python script.

Head to your Google settings (not Gmail settings; you can access by staying signed-in. You should see your email address in the top right corner). Click on My Account and then Sign-in & Security. In the left pane, choose Connected apps & sites. Scroll to the bottom of the page and turn ON Allow less secure apps. Make sure that the settings remain ON by clicking on another menu and coming back to this setting. When I tried it for the first time, the setting seemed to reset itself.

When this is done, the following script should work out of the box:

import smtplib

gmail_user = ''
gmail_pwd = 'your_password'
FROM = gmail_user # sendmail needs the from
TO = ''
message = 'TEST msg'

# SMTP_SSL Example
server_ssl = smtplib.SMTP_SSL("", 465)
server_ssl.ehlo() # optional, called by login()
server_ssl.login(gmail_user, gmail_pwd)
server_ssl.sendmail(FROM, TO, message)
print 'successfully sent the mail'

Voilà! If that was helpful, please let me know. Feel free to shoot your question in case you had issues. I will update this document based on your feedback.

Shailen is a Technical Consulting Engineer at Intel Corporation. He has a Master degree in Computational Science and Engineering from the Technical University of Munich and a Bachelor degree in Electrical Engineering and Computer Science from Jacobs Univerity Bremen. Shailen has conducted research in power modelling for HPC applications and has high interests in the mobile sector. At Intel, Shailen is responsible for the Intel Integrated Native Developer Experience (INDE) suite of software for mobile developers. Shailen comes from the beautiful island of Mauritius. He has a LinkedIn and a Xing profile. Lastly, his name is unique in the world and he admires Bill Gates.

Posted in High Performance Computing

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: