HomeTutorials › Sending An Email Using Python On The Raspberry Pi

Sending An Email Using Python On The Raspberry Pi

Wouldn’t it be nice if your project could email you when it is done a task, has a problem, or just randomly thought the day? Well, with the Raspberry Pi, this is something that can be easily set up with a little Python code and an extra Gmail account. In this tutorial we will go through the steps of setting up a chunk of code that can be easily configured to send an email on command in any Python project!

There are a lot of different operating systems out there for the Raspberry Pi, so we are going to focus on the most popular: Raspbian. We are using the version dated: 2019-7-10 (Pi 4 Compatible) available from the Raspberry Pi Foundations’ Download Page. You don’t need to use the Raspberry Pi 4, any Raspberry Pi will do. However, deviating from the recommended operating system version may result in different / additional steps so if you are very new to this, we recommend following the tutorial exactly.

Requirements:

start

This tutorial requires several items:

Step 1 - Get Everything Prepared

 
Step4

In this short tutorial, we are going to get started with the assumption that you have already set up your Raspberry Pi, installed Raspbian, and have your Python3 editor of choice open and ready to go.

Step 2 - How it works

 

Sending an email with the Pi using Python isn’t that difficult. We are going to create the email content in code and use an external email provider to act as the mail server send the email. Because we are using code to generate the email, we can dynamically create the content we send based on sensor readings, time of day, or just about anything else you can imagine! In this example we are going to use Google / Gmail to provide email services. We will create a Gmail account specifically for this device and give the Pi permission to send with this account. Do not use your normal email address – the email address and password are stored in plain text in your code!

Step 3 – Create a Gmail Account

 
Step4

Head on over to Gmail and create a new email account. You may need to sign out if you are already logged in with an existing account. Once that is completed – move on to step 4!

Step 4 – Set Gmail Permissions

 
Step4

To access a Gmail account using an external device like the Raspberry Pi, permission for “less secure apps” will have to be enabled. When logged in as your new email account you can jump over to https://myaccount.google.com/lesssecureapps and enable this setting. Since most people have several Google accounts, just be sure you are using the right account when you enable this setting!

Step 5 – Coding

 
Step4

With Gmail set up, we are now going to write some basic code. The idea is that this code can be cut and pasted into a project without much need to modify it. We will start with the defining the server connection information and then move on to writing the sender. The sender will take dynamically generated information and use that for the subject line and content of the email. Time to open your favorite Python editor!

Step 6 – SMTP Library

 

First we are going to start by adding in the smtp library reference. This gives us the email tools we are going to need.

import smtplib

Step 7 – Email Variables

 

We need to store a bunch of information for sending out emails as well. The SMTP Server and SMTP port are not going to change, but be sure to update the email address and password in your code to match the credentials for the Gmail account you created earlier.

import smtplib

#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = 'youremail@email.com' #change this to match your gmail account
GMAIL_PASSWORD = 'yourPassword'  #change this to match your gmail password

Step 8 – Email Sender

 

Next, we are going to write the chunk of code that actually sends the email. This creates the email, formats it correctly, creates the connection to Gmail, logs in, and sends the email. It is quite a few lines of code so we are going to put it into a custom Class – that way we can write this code once, but call it any time we want to send an email in our program. There isn’t anything to modify in this section of code so just copy it exactly.

import smtplib

#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = 'youremail@email.com' #change this to match your gmail account
GMAIL_PASSWORD = 'yourPassword'  #change this to match your gmail password

class Emailer:
    def sendmail(self, recipient, subject, content):
        
        #Create Headers
        headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
                   "MIME-Version: 1.0", "Content-Type: text/html"]
        headers = "\r\n".join(headers)

        #Connect to Gmail Server
        session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        session.ehlo()
        session.starttls()
        session.ehlo()

        #Login to Gmail
        session.login(GMAIL_USERNAME, GMAIL_PASSWORD)

        #Send Email & Exit
        session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
        session.quit

sender = Emailer()

Step 9 – Email Contents

 

The Class we wrote in the last step sends out the email. The class takes three arguments (pieces of information we specify when we use the code to send an email) and constructs the email before sending. These three external components are the recipient of the email, a subject line for the email, and the text you want to have in the body of the email. These three pieces of information are stored in three variables (sendTo, emailSubject, and emailContent). This way, our code is capable of sending emails to different people, with different subject lines, and different email content without having to write a different sender for each new contact / email message. Add the three variables and be sure to set the recipient to somewhere you want to receive your first test email

import smtplib

#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = 'youremail@email.com' #change this to match your gmail account
GMAIL_PASSWORD = 'yourPassword'  #change this to match your gmail password

class Emailer:
    def sendmail(self, recipient, subject, content):
        
        #Create Headers
        headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
                   "MIME-Version: 1.0", "Content-Type: text/html"]
        headers = "\r\n".join(headers)

        #Connect to Gmail Server
        session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        session.ehlo()
        session.starttls()
        session.ehlo()

        #Login to Gmail
        session.login(GMAIL_USERNAME, GMAIL_PASSWORD)

        #Send Email & Exit
        session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
        session.quit

sender = Emailer()

sendTo = 'anotheremail@email.com'
emailSubject = "Hello World"
emailContent = "This is a test of my Emailer Class"

Step 10 – Calling the Email Class

 

Now that we have everything set up – sending an email is as simple as calling the Emailer Class with the three arguments (sendTo, emailSubject, and emailContent). It will then create and send the email based on those parameters.

import smtplib

#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = 'youremail@email.com' #change this to match your gmail account
GMAIL_PASSWORD = 'yourPassword'  #change this to match your gmail password

class Emailer:
    def sendmail(self, recipient, subject, content):
        
        #Create Headers
        headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
                   "MIME-Version: 1.0", "Content-Type: text/html"]
        headers = "\r\n".join(headers)

        #Connect to Gmail Server
        session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        session.ehlo()
        session.starttls()
        session.ehlo()

        #Login to Gmail
        session.login(GMAIL_USERNAME, GMAIL_PASSWORD)

        #Send Email & Exit
        session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
        session.quit

sender = Emailer()

sendTo = 'anotheremail@email.com'
emailSubject = "Hello World"
emailContent = "This is a test of my Emailer Class"

#Sends an email to the "sendTo" address with the specified "emailSubject" as the subject and "emailContent" as the email content.
sender.sendmail(sendTo, emailSubject, emailContent)  

Run this code by hitting “F5” on the keyboard, an email should be received at the receiving address a moment later – as simple as that. Going forwards, you can copy and paste this code into a Python 3 project to provide email sending capabilities with ease!

An Example: Email on Button Press

 

Here is a quick example of this code being used to send an email anytime a button is pressed. To try it out, connect a momentary button to GPIO 17 and GND. You will also need to change your Gmail Sender Email and Password, along with the recipient at the bottom.

import smtplib
import RPi.GPIO as GPIO
import time
 
#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = 'youremail@email.com' #change this to match your gmail account
GMAIL_PASSWORD = 'yourPassword'  #change this to match your gmail password

#Set GPIO pins to use BCM pin numbers
GPIO.setmode(GPIO.BCM)

#Set digital pin 17(BCM) to an input
GPIO.setup(17, GPIO.IN)

#Set digital pin 17(BCM) to an input and enable the pullup 
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#Event to detect button press
GPIO.add_event_detect(17, GPIO.FALLING)

 
class Emailer:
    def sendmail(self, recipient, subject, content):
         
        #Create Headers
        headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
                   "MIME-Version: 1.0", "Content-Type: text/html"]
        headers = "\r\n".join(headers)
 
        #Connect to Gmail Server
        session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        session.ehlo()
        session.starttls()
        session.ehlo()
 
        #Login to Gmail
        session.login(GMAIL_USERNAME, GMAIL_PASSWORD)
 
        #Send Email & Exit
        session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
        session.quit
 
sender = Emailer()

while True:
    if GPIO.event_detected(17):
        sendTo = 'anotheremail@email.com'
        emailSubject = "Button Press Detected!"
        emailContent = "The button has been pressed at: " + time.ctime()
        sender.sendmail(sendTo, emailSubject, emailContent)
        print("Email Sent")

    time.sleep(0.1)
    
 

Once the email and password fields are updated, run this code by hitting “F5” on the keyboard. When the button is depressed, an email should be received at the receiving address a moment later with the time the button was pressed.

Have A Question?
If you have any questions, or need further clarification please post in the comments section below; this way future users of this tutorial can see the questions and answers!

Parts Used In This Tutorial:

5 comments

  1. Trent
  2. Nils

Leave a Reply