Python on the Pi – Sending mail

Set to ON

I’m busy experimenting with the Rasberry Pi and doing a little Python programming. One of the goals I had was to be able to send an email for status messages.

First things first, make sure your Pi is up to date and upgraded to the latest versions

sudo apt-get update

sudo apt-get upgrade

When all is complete you need to do two installs

sudo apt-get ssmtp mailutils

Note the double s

Note on GMail you will need to open a new account and set it that non google applications be allowed to use it (Less secure). Note your privacy on this mail account shouldn’t be an issue.

Once your account is created and signed in on line, click on your profile icon, then click on “Manage your Google Account“. Click on “Security” and scroll down to “Less secure App access” and switch it ON. That’s it, now you’re ready to play!

Simple python code. Substitute your own mail addresses.

import smtplib

smtpUser = 'yourmail@gmail.com'
smtpPass = 'yourpassword'

toAdd = 'towho@gmail.com'
fromAdd = smtpUser

subject = 'Python mail send test'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'From within a Python script'

print header + '\n' + body

s = smtplib.SMTP('smtp.gmail.com',587)    

s.ehlo()
s.starttls()
s.ehlo()

s.login(smtpUser, smtpPass)
s.sendmail(fromAdd, toAdd, header + '\n\n' + body)

s.quit()

Works pretty well. Now to implement this facility in my home brew rasberry pi based trail camera!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s