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:

or -> "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.

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named

# Where will the mail seem to come from?

# The full hostname

# 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

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"

I got:

$ send-mail: Cannot open

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"

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
subject: Test


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

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

import smtplib
smtpUser = ''
smtpPass = 'superSecretPassword'
toAdd = ''
fromAdd = smtpUser
subject = 'Python Test'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'From within a Python script'
s = smtplib.SMTP('',587)
s.login(smtpUser, smtpPass)
s.sendmail(fromAdd, toAdd, header + '\n\n' + body)

Save it, then run it:

$ python



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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