Send Email with a Raspberry Pi and Python
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:
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.
This is great. I have been trying to figure out how to use this for the longest time. This is a long and extensive review. It really helped me out a lot. I will bookmark your site and share it on my social media sites.
Thanks
Thanks
Glad you found it helpful, I tried to provide as many different options as I could think of
I think this is the best article I have found on sending an email from python. I used it to send a text alert to my iPhone if a certain condition occurred while running a program.
Thanks again.
Thank Jack, always nice to hear back that someone found it useful
Awsome post!
I was looking for something to send backup files from Raspberries. It works gr8.
Thank you so much!
Thanks Peter
Really appreciate that
So is this all that needs to be out into the python file to have it send the email. I have been running this by itself and it’s done nothing so far
Hi Nathanial
Sorry to hear that it isn’t working you, If you drop me a message via my contact page with a bit more information about the problem I’d be happy to try and work it out with you.
One of the very few pages with terrific information.
Thanks
Vik
Glad you found it helpful Vik
Hello
I would like to autoforward received emails and add signature to them.
Its for a printer.
Is it possible ?
Hi, it probably is but it’s not something that I have ever looked into, I would suggest that you maybe look at a custom python email library like pyzmail, they may provide a solution to your problem.
Hello,
How do I install the smtplib package ?
thanks
Hi there is no need to install the smtplib package as it is a native library in Python. All that you need to do is place the following line at the top of your code
import smtplib
and the functions will be available for you to use in your script.