Send Email with a Raspberry Pi and Python

by | Jun 15, 2022 | 14 comments

Send Email with a Raspberry Pi

 

Sending email with a Raspberry Pi Python program can be very useful when you want an alert, to receive a set of results or find out if a set of conditions have been reached among other things. To achieve this we need to create a python script that uses the smtplib native library. Through this I will show you how to create a simple email right through to a more complete email with subject lines, attachments, extended body text and the ability to send to multiple recipients,to achieve more than a simple email we will need in include some additional modules, email.mime.multipart and email.mime.text.

To run the python script on the Pi I am assuming that you have the latest version of Raspian 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. The code below should work on both python 2.7 and python 3.2 that are used on the Pi.

A further consideration is your internet connection security, given that the scripts below will contain your email address and password in the code 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.

 

Simple Email:

 

Warning: Due to Google using oauth 2.0 security normally a 2 stage check is required to access the server, this can be overcome by allowing less secure apps on your account

 

To send a simple email with no subject line we can use the following code

 

#!/usr/bin/env python

import smtplib

server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(“[email protected]“, “FromUserPassword“)
msg = “This is a simple email test!”
server.sendmail(“[email protected]“, “[email protected]“, msg)
server.quit()

 

Note: In this example I am using the gmail smtp server, if you are sending from an outlook or yahoo address replace smtp.gmail.com with one of the following:

 

smtp-mail.outlook.com

smtp.mail.yahoo.com

 

Replace the entries highlighted in blue with your email address and password and the intended recipient. The msg=” ” is the mesage that will be contained in the body of your email.

 

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.

 

#!/usr/bin/env python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

fromaddr = “[email protected]
toaddr = “[email protected]

msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”
body = ‘This is an extended email test’
msg.attach(MIMEText(body, ‘plain’))

server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.ehlo
server.starttls()
server.login(fromaddr, “FromUserPassword“)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

 

Again in this example you just need to enter your details in the blue highlighted entries in the relevant spots 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’] = ” ”

 

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.

 

#!/usr/bin/env python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = “[email protected]
toaddr = “[email protected]

msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”body = ‘This is an extended email test’
msg.attach(MIMEText(body, ‘plain’))

filename = “AttachmentFileWithExt
attachment = open(“FullPathToFile“, “rb”)

part = MIMEBase(‘application’, ‘octet-stream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, “attachment; filename= %s” % filename)
msg.attach(part)

server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(fromaddr, “FromUserEmailPassword“)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

 

In addition to adding your own information you need to set the name of the file to attach with it’s extension  (eg. testfile.txt) and the full path to where the file can be found (eg. /home/pi/testfile.txt).



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.

 

#!/usr/bin/env python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = “[email protected]
toaddr = “[email protected]

msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”
f = open(“PathToEmailBodyTextWithExtension“)
body = f.read()
msg.attach(MIMEText(body, ‘plain’))

filename = “AttachmentFileWithExt
attachment = open(“FullPathToFile“, “rb”)

part = MIMEBase(‘application’, ‘octet-stream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, “attachment; filename= %s” % filename)
msg.attach(part)

server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(fromaddr, “FromUserEmailPassword“)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

 

Here you need to add the full path name of the text file containing your body text to the line f = open(” “) eg. /home/pi/email_body_text.txt.

 

Email with Multiple Recipients:

 

Finally if you want to send the email to more than one recipient we need to present the all the receiving email addresses to the server.sendmail function.

 

#!/usr/bin/env python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = “[email protected]
toaddr = “[email protected],[email protected],[email protected]
alladdr = toaddr.split(“,”)

msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”
f = open(“PathToEmailBodyTextWithExtension“)
body = f.read()
msg.attach(MIMEText(body, ‘plain’))

filename = “AttachmentFileWithExt
attachment = open(“FullPathToFile“, “rb”)

part = MIMEBase(‘application’, ‘octet-stream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, “attachment; filename= %s” % filename)
msg.attach(part)

server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(fromaddr, “FromUserEmailPassword“)
text = msg.as_string()
server.sendmail(fromaddr, alladdr, text)
server.quit()

 

When entering your own information the “toaddr” variable is now where you can add the comma separated recipients. As a bonus 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 show in the code below.

 

#!/usr/bin/env python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = “[email protected]
toaddr = “[email protected],[email protected]
ccaddr = “[email protected],[email protected],[email protected]
bccaddr = “[email protected]
alladdr = toaddr.split(“,”) + ccaddr.split(“,”) + [bccaddr]msg = MIMEMultipart()

msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”
f = open(“PathToEmailBodyTextWithExtension“)
body = f.read()
msg.attach(MIMEText(body, ‘plain’))

filename = “AttachmentFileWithExt
attachment = open(“FullPathToFile“, “rb”)

part = MIMEBase(‘application’, ‘octet-stream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, “attachment; filename= %s” % filename)
msg.attach(part)

server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(fromaddr, “FromUserEmailPassword“)
text = msg.as_string()
server.sendmail(fromaddr, alladdr, text)
server.quit()

 

With these scripts you will now be able to send emails in whatever style you like be that formal or just a simple alert. All the python code for the above emails is available for both 2.x and 3.x 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.

 

 

Pin It on Pinterest

Share This