Send Email from Raspberry Pi Command Line and/or Python Script

Send Mail from Raspberry Pi Using SSMTP

Raspberry Pi B: Wheezy.

First, you need a Gmail account to use as the actual mail client. You will forward the email from the Pi to Gmail.

Set Up Gmail

Log in to Gmail, and then click here:

https://www.google.com/settings/security/lesssecureapps

or

myaccount.google.com -> "Sign-in & security" -> "Allow less secure apps: ON"

This is the location where you change your security settings. You need to set “Allow less secure apps” to ON.

Install SSMTP on Pi

$ sudo apt-get install ssmtp

Now edit the configuration file.

$ sudo nano /etc/ssmtp/ssmtp.conf

Make the following changes:

# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=postmaster

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com:465

# Where will the mail seem to come from?
#rewriteDomain=

# The full hostname
hostname=MyRaspbi

AuthUser=myEmailAddress@gmail.com
AuthPass=superSecretPassword
UsSTARTTLS=YES
UseTLS=YES

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
#FromLineOverride=YES

Note that the port for the conf file is 465 – I attempted to use 587, but it failed. The odd thing is that when I use a Python script to do the same thing, I have to use port 465. [scratches head]

When I ran it with 587:

$ echo "Hello inbox" | mail -s "Test" theToEmailAddress@hotmail.com

I got:

$ send-mail: Cannot open smtp.gmail.com:587

But changing the port to 465 made it happy. Also note that it fails if you add an exclamation point to the subject:

$ echo "Hello inbox!" | mail -s "Test" theToEmailAddress@hotmail.com

Will fail.

Note: I installed this the same way on Debian Jessie, and it did not have Mail installed. Instead, I tested it by entering the following, on each line, then after the last line, pressed Ctrl+D.

$ ssmtp theToEmailAddress@hotmail.com
subject: Test
Hello
$

CTRL+D.

Also, I discovered that Mpack (module that allows email attachments) was already installed.

Create Python Script

Create your python script to send the mail:

$ sudo nano sendMail.py

Enter the following (be careful to use single quotes where applicable):

import smtplib
smtpUser = 'myEmailAddress@gmail.com'
smtpPass = 'superSecretPassword'
toAdd = 'theToEmailAddress@hotmail.com'
fromAdd = smtpUser
subject = 'Python Test'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'From within a Python script'
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()

Save it, then run it:

$ python sendMail.py

Tada!

Leave a comment