Send Email with a Raspberry Pi and Python
Sending an email with a Raspberry Pi Python program can be very useful when you want an alert, or to send a large number of personalized emails or perhaps just automate the sending of common emails among other things. To achieve this we need to create a python script that uses the smtplib and email.MIME native libraries.
In this tutorial I will show you how to create a simple email right through to a more complete email with subject lines, attachments, extended body text with HTML and the ability to send to multiple recipients.
To run the python script on the Pi I am assuming that you have the latest version of Raspbian and have the ability to connect to your Pi either through SSH with Putty and FTP with Filezilla, or directly with a keyboard and monitor, if you haven’t set-up your Pi yet then check out my getting started section.
A further consideration is your internet connection security, given that the scripts below will contain your email address and password in the code in plain text it may be wise to consider getting another Gmail address or similar just for the purpose of sending automated emails rather than using your normal day to day address and risking it being compromised.
In this tutorial I will be using the following materials:
- Raspberry Pi (2, 3 or 4)
- Micro SD Card
- Power Supply
- Ethernet Cable or Wi-Fi Dongle (Wi-Fi is onboard the Pi 3 and 4)
- Raspberry Pi Case (Optional)
In This Article
- Send a Simple Email
- Send an Email with a Subject Line
- Send an Email with an Attachment
- Send an Email with an Imported Body Text
- Send An Email with HTML Body Text
- Send an Email to Multiple Recipients
- Send Multiple Personalized Emails
Send a Simple Email
To send a simple email with no subject line we can use the following code, first we import the smtplib library and establish the server that we are going to use, for this tutorial I will be using Gmail. Next, establish a connection to the server using server.login and your Gmail credentials, finally send all the email addresses and the message to the server, finally, close the server connection.
Note: There are limits on the number of requests that can be made to the server each day, these limits differ depending on the provider.
In this example, I am using the Gmail SMTP server, if you are using an Outlook or Yahoo server then use one of the following –
- ‘smtp-mail.otlook.com’, 587
- ‘smtp.mail.yahoo.com’, 587
Replace the relevant entries above with your email address, password and the intended recipient. The msg=” “ entry is the message that will be contained in the body of your email.
Send An Email with a Subject Line
While a simple email may suffice as an alert just to yourself if you intend the email to look slightly more professional then including a subject line may be important. To achieve this you need to use Python’s “email.mime” module. Importing the MIME (Multipurpose Internet Mail Extensions) Multipart and Text functions will allow you to build up an email in sections.
Again in this example you just need to enter your details in the relevant locations in the script, In this case, the message in the body of the email is entered in the body=” “ section, the subject line of your email will contain your entry in the msg [‘Subject’] = ” ” entry
Send An Email with an Attachment
To take it one step further if you want to include an attachment with your email the following code can be used. In this step we add the MIMEBase and encoders functions to encode binary data into printable ASCII characters that can be handled by the email server.
In addition to adding your own information, you need to set the name of the file to attach with its extension (eg. testfile.txt) and the full path to where the file can be found (eg. /home/pi/testfile.txt).
Send An Email with Extended Body Text
If you need to send an email with more text in the body where it is impractical to write it directly into the python code then a text file can be created with the body of the email and then read into the script.
Here you need to add the full pathname of the text file containing your body text to the line ftext = open(” “) eg. /home/pi/email_body_text.txt.
Send An Email with HTML Body Text
If you want to send an email that is a bit fancier with colors, bold type, italics, etc, or if you want to add any images, hyperlinks, or responsive content, then HTML comes in very handy. The code below opens and reads two files, one a .txt file and the other a new .html file, it is necessary to have both versions available as not all email clients display HTML content by default, and some people choose only to receive plain-text emails for security reasons, having both versions ensures that the body content is displayed.
As the email client will render the last MIMEmultipart attachment first, make sure to add the HTML file after the text file, below is a simple example of an HTML file.
In addition to adding your own information in the code above, make sure that the word “alternative” is in the line msg = MIMEMultipart(“alternative”), this will take both of the MIMEText objects and combine them into a single message with two rendering options.
Send An Email to Multiple Recipients
If you want to send the email to more than one recipient we need to present all the receiving email addresses to the server.sendmail function. If you don’t have multiple email addresses to test with but you have a Gmail address you can use the + sign to create multiple addresses in the following format –
This will allow you to emulate multiple addresses that all go to the same inbox.
When entering your own information the “toaddr” variable is now where you can add the comma-separated recipients.
If you want to add Cc or Bcc recipients then you will need to add the “ccaddr” and “bccaddr” variables and configure the “alladdr” variable to combine all the intended recipients into one string as shown in the code below.
Send Multiple Personalized Emails
Let’s say that you have to send out the results of a test to a large number of students, it would be time-consuming to send out personalized emails individually, fortunately, through the use of a CSV (Comma Separated Variable) file python makes this simple.
First, you need to create and save a CSV file with all the relevant information, this is basically a table with the column headings and can normally be easily created using spreadsheet software. In this example, I will use the CSV data shown below which details the user, their email address, their score in the test and the resultant grade.
Next, you need to create the personalized body text and HTML files, we will use these files as templates to insert the personalized details of each email through the use of the str.format() function and curly bracket placeholders in Python. Below is an example of both the text and HTML files with the placeholders shown.
In order to access the data in the CSV file from Python, we need to import the CSV module, from this we will use the csv.reader function to loop through the file one line at a time and apply the data to the common formatted email body.
Again in addition to adding your own information in the code above, make sure that the word “mixed” is in the first msg = MIMEMultipart(“”) and that “alternative” is in the second entry. This will ensure that both the attachment and the two rendering methods (Text and HTML) will be included with the message.
With these scripts, you will now be able to send emails in whatever style you like be that in the form of multiple personalized emails or just a simple alert. All the python code for the above emails is available on MyHydropi Github Repository.
If you have any thought’s about this article, improvements or errors let me know in the comments below and if you found this helpful, why not share it with others.