This article will explore simple sending email using Python and how it can be integrated in your existing data science projects.

Table of Contents


Introduction

After building any data science project and deploying it, we always want to make sure it’s running smoothly and be notified if there are any errors. When you are working on one main project every day, it may be much easier to keep an eye on it, than if you are in charge of four projects for example. Instead of checking the code and output every time, we’d rather be notified when the code was executed successfully, or if there were any issues with it. This is why we introduce a topic of building email notifiers in Python. What we want to achieve is an automated email being sent to our email address with a trigger of your choice. Let’s look into how we can automate this process and send email in Python.

In this tutorial you will learn how to send automated emails using Python. We will work with a Gmail address (but you can extend the same code to work with any other email service provider).

To continue in this article, please import the smtplib library:


import smtplib

Send Email using Python

There are four main steps in sending an email using Python:

  1. Connect to SMTP server
  2. Log in into the server
  3. Create a message
  4. Send the email

Step 1: Connect to SMTP server using Python

The SMTP (Simple Mail Transfer Protocol) is a communication protocol for email transmission. Every email service provider has an SMTP address which can be found in the settings of your mail client. And we we will also need an SMTP port (in our case we will use port 587).

A few examples: Gmail SMTP is smtp.gmail.com, Outlook SMTP is smtp-mail.outlook.com. Both of these can send emails via port 587.

Let’s go ahead and create a server variable which will we an smtplib instance with our email SMTP information:


server = smtplib.SMTP(host='smtp.gmail.com', port=587)

Next we need to “identify” our server and let it start “talking” to the SMTP:


server.ehlo()

And finally, we need to establish a TLS (Transport Layer Security) connection for communication between the email server and the client:


server.starttls()

All of the above steps combines establish a secure connection for us to the email server. You can think of it as you just went on www.mail.google.com.


Step 2: Log in into the server using Python

Now we need to log in into our account.

This part is very short and all that is required to do is execute one line of code with your email login and password credentials to log in:


server.login('your email address', 'your password')

This is essentially the same as going into Gmail sign in page, entering your credentials, and clicking “Login”. At this point we are inside of our email account.


Step 3: Create a message

After logging in into our email account, we want to write a new email. The email will contain two parts to it: a subject and an actual message. Let’s create both of these:


subject = 'This is my subject'
body = 'This is the message in the email'

In order to process this message through smtplib, we will need to make one object containing both the subject and the body. This can look a little unusual, but it is the formatting that needs to be done in order for the client to process the message:


message = f'Subject: {subject}\n\n{body}'

This creates a formatted string which the email client recognizes and uses the first part of it as the email subject, and the second part as the email text.


Step 4: Send the email using Python

At this point, we logged in into our email account and created a message. Now we just need to send it and exit the email account. In order to send it, we need three components: sender’s email, recipient’s email, and the message:


server.sendmail('your email address', 'recipient email address', message)
server.quit()

Perfect! You’ve just sent your first email using Python!


Send email using Python functions

In general, when working with automated email senders, we prefer to have them as reusable functions rather than creating a raw Python script.

First let’s try to create one function with all of the above steps in one place:


def send_email(subject, body):
    server = smtplib.SMTP(host='smtp.gmail.com', port=587)
    server.ehlo()
    server.starttls()
    server.login('your email address', 'your password')
    message = f'Subject: {subject}\n\n{body}'
    server.sendmail('your email address', 'recipient email address', message)
    server.quit()

Once we set it up in the functional form, it’s reusable in any parts of your existing project script. But there is a catch, if, for some reason, the email doesn’t go through successfully, it will break the overall script of the project you are running. So let’s add some guard rails in order to prevent your main project script execution breaks.

In order to help us do it, we will use the Python try/except statement. What it will do is attempt (try) to send the email, but in case it fails, it will allow the remainder of your project script to run:


def send_email(subject, body):
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login('your email address', 'your password')
        message = f'Subject: {subject}\n\n{body}'
        server.sendmail('your email address', 'recipient email', message)
        server.quit()
    except:
        pass

In this functional form you can add it anywhere in your project script and let it run. Keep in mind that this function now requires two arguments: subject and body. So when you add it and want it to be executed, it should be something like this:


send_email('this is the subject', 'this is the body')

The above function should sent an email having “this is the subject” as the subject of the email and “this is the body” as the email’s content.


Conclusion

This article focused on exploring the process on how to send email in Python. It should be a good foundation to understand the process and have the knowledge to integrate it into an existing data science project.

Check out more of my Python Programming tutorials.

Feel free to leave comments below if you have any questions or have suggestions for some edits.