How To Send Email With Python

Steven Zych
5 min readDec 11, 2020

You want boilerplate code and I get that — it’s immediately below this. But I encourage you to read on after, to do more than just a grab and dash. In the sections following the boilerplate code, I talk about:

  • What the boilerplate code is actually doing, line by line
  • What SMTP (Simple Mail Transfer Protocol) actually is
  • Use cases for SMTP in data science, including the most recent way I’ve used it

Come along for the ride and you’ll be glad you did.

Boilerplate Code

First off, there’s no installs to be done. If you’re running Python on your machine, the library smtplib (SMTP [Simple Mail Transfer Protocol] library) should already be on it. Provided you aren’t missing that for some reason, here’s all you need to establish a connection with your email and send a test:

Note: This example is based on Gmail. To use smtplibwith Gmail, you’ll also need to set up an app password. Details on that after the code.

import smtplibserver = smtplib.SMTP(“smtp.gmail.com”, 587)server.starttls()server.login(“sender_email@gmail.com”, “sender_password”)message = “Subject: This is a subject!\n\nAnd this is the body!”server.sendmail(“sender_email@gmail.com”, “recipient_email@gmail.com”, message)

Setting Up An App Password

If you’re using Gmail (and surely other sites, but I can only speak to what I’ve done), you’ll need a secondary app password for smptlib to work right. Passing it your default password is likely to throw an error, and flood your phone or inbox with “An Unauthorized Device Tried To Access Your Account” and so on.

So how do we set up an app password? Do the following steps:

  • Enable 2-step authentication on your account. This can be found in: Manage Your Google Account > Security > 2-Step Authentication
  • Navigate to Security > App Passwords
  • Under “Select App” choose “Other”
  • Name the app “SMTP”
  • You should see a 16-character string. Save this locally like you would an API key. It will not be shown again
  • Congrats, you have an app password!

To double check that it works, run the code above and sub in your own email, and that app key.

Boilerplate Code Explanation

As promised, I’ll now be breaking down each individual line of this code to illustrate what’s happening. I find a lot of basic tutorials don’t do this, assuming that things are intuitive enough to negate an explanatory need. Let’s right that wrong here:

import smtplib

In Python, typing import followed by the name of a package or library effectively brings that prewritten code “in” to your notebook or workspace. In this case we are bringing smtplib “in” to our notebook, allowing us to call all the methods we see below, and instantiate an SMTP object.

server = smtplib.SMTP(“smtp.gmail.com”, 587)

Here we’re creating an SMTP object (which is a unique instance of the SMTP class). You can think of this as our connection to the email site in question. A fuller, more jargon-y description can be found here. The 587 argument that is passed when we instantiate (create) this object is not something you’ll likely ever change, and it refers to the port on which this operates.

server.starttls()

This method establishes a secure connection. It allows for all following commands to be encrypted. Again, a more complex description is available here.

server.login(“sender_email@gmail.com”, “sender_password”)

Another SMTP class method. Truly no different from logging in to your email in a browser, with the caveat that your pre-made app password is going to bypass those pesky “Unauthorized Attempt Made” emails and texts you may have gotten before.

message = “Subject: This is a subject!\n\nAnd this is the body!”

Again, quite straightforward. Here we’re just assigning the value of a message to pass into the next line of code. It just looks a little cleaner this way. Also, by writing “Subject:” and using the two line breaks “\n\n” we’re able to format a separate subject and body within our email in a single line of code.

server.sendmail(“sender_email@gmail.com”, “recipient_email@gmail.com”, message)

Lastly, this line of code actually sends the email, per the method name, sendmail(). As a reminder, the sender_email@gmail.com needs to be the same as the email you logged in with / supplied the password for, or this will not work. The recipient email, of course, also needs to be changed.

So What Is SMTP?

In short, SMTP is “Simple Mail Transfer Protocol.” It is an internet standard that allows for the relay of information via email. When we say it’s a “standard” we mean that it is a protocol widely-recognized as possessing a level of “technical maturity and … provides significant benefit to the Internet community.” Having standards such as these allow different developers from all over the world to create and exchange software and ideas that can more easily work with one another. Imagine that overwhelming complexity and sluggishness of idea-exchange we’d encounter if every developer had their own standards for how the Internet ought to work! You could similarly imagine a contemporary world without Unicode, and ponder those horrors.

Use Cases

Enough beating around the bush: Why do you want to use this? Well, from a developmental standpoint, email functionality makes perfect sense for an app: You might want to notify users when an account is breached, send promotional materials, or communicate with other members of your workspace via email automation. The list goes on.

Akin to that last idea is my own smtplib implementation in a data-science framework. For my capstone project at Flatiron School, I used Twitter livestreaming, sentiment analysis, and a simple chatbot to automate user outreach on Twitter. When users were seen tweeting positively about a brand or topic, a chatbot would reach out, ask if they’re interested in collaborating, and ideally: An email would be automatically sent to a human employee with the user’s ID, so that they could finish the deal. Take a look at the Emailer class I built for this, and its integration with the final Twitter streamer.

While the automated emailing itself didn’t directly deal with big data or analysis, it was the integral final pin in this process that rested on a data-science foundation. I encourage you to explore that repo, and sound off in the comments here with any use cases of your own! Lastly, I’d like to plug this blog post, which shows implementations for the inverse of this, data analysis on retrieved emails.

Happy coding!

--

--