BC Robotics

Sending An Email Using Python On The Raspberry Pi

  PRODUCT TUTORIAL

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:

This tutorial requires several items:

0%

Step 1 - Get Everything Prepared

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. 

10%

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. 

20%

Step 3 – Create a Gmail Account

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!  

30%

Step 4 – Set Gmail Permissions

To allow a device to use your Gmail account you will need to have 2-factor authentication enabled. This can be done through your Google Account under the Security tab – https://myaccount.google.com/security .

Once logged in, enable 2-Step Verification (if it is not already enabled). 

Once 2-Step Authentication is enabled, we can create an App Password specific to the Raspberry Pi we are sending emails from. This ensures the account password / Gmail password does not need to be stored in plain text in your code, just a device specific password. 

Click on “App Passwords” 

In the App Passwords screen, click the “Select Device” dropdown, and select “Other”

In the text box that appears, name your device. This name is just for your reference, so make it something meaningful. Once that is done, click “Generate” to create the App Password. 

Copy the password that appears – and paste it somewhere temporary while we get the code organized. This is going to be used as your Gmail Password when connecting from this device. 

40%

Step 5 – Coding

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!  

50%

Step 6 – SMTP Library

				
					import smtplib
				
			

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

60%

Step 7 – Email Variables

				
					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 app-password
				
			

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.  

70%

Step 8 – Email Sender

				
					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 app-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()
				
			

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. 

80%

Step 9 – Email Contents

				
					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 app-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"
				
			

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.

90%

Step 10 – Calling the Email Class

				
					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 app-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)  
				
			

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. 

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!

100%

An Example: Email on Button Press

				
					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 app-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)
    
				
			

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 app-password, along with the recipient at the bottom. 

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. 

38 thoughts on “Sending An Email Using Python On The Raspberry Pi”

Leave a Reply

Your email address will not be published.

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the comparison bar
Compare