How to send an email from a Gmail account with Python

William Ryan
7 min readFeb 9, 2016

--

I recently had to figure out how to send emails automatically, and it took long enough to figure out I thought I would share. Sending emails with Python is also a great introduction to writing programs to carry out menial tasks for you, which I’m a huge fan of. In this case, I’m sending an email from a Gmail account which I have already set up. I’m going to go through the steps methodically and try to explain each as I go assuming a minimal knowledge of both Python and the mechanics behind email, since I would’ve found that useful when starting out myself, but if you’d rather just see the final code you can skip to the end.

Getting set up

The first thing you need to do is make sure you have a Gmail account set up which you can send emails from, and have it set to allow less secure apps to access it — this will let you log into it with Python. You can find the page on how to do this here. You’ll also need to have Python 3 installed —personally, I use Anaconda, which gives you Python and a bunch of libraries for scientific programming.

Second, you’ll need to install a few libraries which we’ll be using:

  1. smtplib, for working with email servers (SMTP = Simple Mail Transfer Protocol).
  2. getpass, for prompting the user for a password without echoing what is typed to the console. A normal input() command would mean that your password would show up in plain text in your console, which is not what you want.

You can install these with the following command in your command prompt (terminal for Macs) using the package management system pip, which should come with your installation of Python:

pip install smtplib getpass

If you’re feeling ambitious, this also isn’t a bad time to use Github, but that’s beyond the scope of what I can write about here. This is a good tutorial, and this is a good client to use if command line interfaces are intimidating.

Now we’re ready to start writing the program — if you’re using Anaconda, go ahead and open Spyder, the editor included with your installation. Otherwise, open whichever Python IDE you like.

How to write the program, step-by-step

The first thing we’ll do is give the program our username and password for the Gmail account we want to send messages from. We could store these as variables, but it would we really insecure to just have our username and password sitting there in our program for anyone to find. Instead, we will prompt the user for their username and password each time they run the program. This takes a little bit longer , but takes less time than apologizing to everyone who got sent spam emails from you when you accidentally pushed your code to a public Github repository.

# Ask the user for their username
input(username)
#Ask the user for their password
getpass(password)

Then we need to connect to Gmail’s servers and log on.

To do this we start a new session using the SMTP function from the library smtplib. This function takes two arguments, the URL of the SMTP server and the port used. In our case, we are using gmail, so the URL is smtp.gmail.com and the port is 587. If you’re using another provider, you can find a big list of common URLs and ports here.

session = smtplib.SMTP(‘smtp.gmail.com’, 587)

Then we are going to use some basic SMTP commands to connect to the server. These basic SMTP commands are explained here. You might be familiar with POST, GET, PUT and DELETE commands from working with HTTP servers and RESTful APIs — these are basically the equivalent set of commands for SMTP servers. If that wasn’t a helpful analogy, just forget about it. All you need to know is that SMTP commands are the basic commands which any SMTP server has to be able to support — think of them as the minimum number of verbs which need to be in the email server’s vocabulary.

First, we need to use EHLO to identify ourselves to the server and start talking to it. Then we’ll send it our log in information for the account we want to use. First, we use STARTTLS (Start Transport Layer Security) to let the server know that we’d like to start communicating in encrypted messages instead of regular plain text. Once we’re encrypted, we’ll then use LOGIN to send it our username and password to the server and get authenticated.

#Initiate connection to the server
session.ehlo()
#Start encrypting everything you're sending to the server
session.starttls()
#Log into the server by sending them our username and password
session.login(username, password)

Now we are ready to start sending mail.

An email message has a few basic components:

  1. The header of the email— includes the name of the email sender and recipient, the subject of the email, and some notes about how to format it.
  2. The body of the email — the actual body text and content of the email.

Let’s start by constructing the headers of the email by defining a new variable called headers:

recipient = "address@gmail.com"headers = “\r\n”.join([“from: " + username,
“subject: Hello”,
“to: " + recipient,
“mime-version: 1.0”,
“content-type: text/html”])

As you can see, we’ve defined the basics of who we want to send it from (this should be just your Gmail you authenticated with), the subject and who you want to send it to. We’re also defining the version of MIME we want to use (MIME is the standard format for email), and defining our content as text which could use HTML — this will let us use HTML to format the body of our email if we want to be fancy.

We’ve put each of the items in our header into a list, and used the .join() command to combine them all into one string with “\r\n” in between them. “\r\n” is a special character which will create a new line, so when the header is sent to the email server, each of our items will be on a separate line.

Then we just need to write out the body of our email. We’ll store it in a variable so it’s easy to change later. You can include HTML formatting in your email — just write it into your string, and it’ll show up more or less like on a website. If you want to do something fancier you can add CSS and other styling, but for now let’s keep it basic:


body_of_email = "Here's my email body content. I can put HTML in this if I want to, like a <br> line <br> break!"

Finally, we just need wrap up all our content together, headers and body, and desperate it with line breaks again. Then we pass it to the sendmail function of smtplib and our email is sent! Finally, we will close out our session with the QUIT command.


content = headers + “\r\n\r\n” + body_of_email
session.sendmail(gm_username, recipient, content)
session.quit()

Putting it all together

Combining all the above code together, we have the following program:

#Import the libraries we need#SMTPlib for interacting with SMTP servers and sending emails
import smtplib
#Getpass for getting our password without showing it to everyone
import getpass
# Ask the user for their username
input(username)
#Ask the user for their password
getpass(password)
session = smtplib.SMTP(‘smtp.gmail.com’, 587)#Initiate connection to the server
session.ehlo()
#Start encrypting everything you're sending to the server
session.starttls()
#Log into the server by sending them our username and password
session.login(username, password)
#Define the recipient of the email
recipient = "address@gmail.com"
#Enter the headers of the email
headers = “\r\n”.join([“from: " + username,
“subject: Hello”,
“to: " + recipient,
“mime-version: 1.0”,
“content-type: text/html”])
#Enter the text of the body of the email
body_of_email = "Here's my email body content. I can put HTML in this if I want to, like a <br> line <br> break!"
#Tie the headers and body together into the email's content
content = headers + “\r\n\r\n” + body_of_email
#Send the email!
session.sendmail(username, recipient, content)
#Close the connection to the SMTP server
session.quit()

What to do next?

Hopefully this was a useful introduction to sending email with Python! If you want to expand on this program, good avenues to explore might be:

  • Sending custom emails to multiple recipients using a .csv to draw information about them (please don’t spam anyone though)
  • Making the body of the emails you send prettier with HTML and CSS
  • Scheduling emails to yourself as reminders or notifications when something happens, like your code completing

I know that realizing how much could be automated with Python was really exciting for me — it’s really clear how programming in Python can make your daily life easier right away. If you want to learn how to do more things like this, I would highly recommend the (free!) book Automate the Boring Stuff with Python for an introduction to some of the things Python can do for you.

For a more general introduction to Python, a lot of people like Learn Python the Hard Way (though it is in Python 2, so if you want to translate what you learned to 3 you’ll want to reference something like Dive Into Python 3). Personally, I ended up using an Intro to Comp Sci textbook, but it goes beyond just Python to broader computer science topics.

To keep updated on future posts, follow @thewilliamryan

--

--