Sending Email from the Raspberry Pi

Lets say you are like me, and all of your ‘friends’ are really robots.  My most recent friend, the Raspberry Pi needs to be able to send me email.  The process is pretty easy, but there are a few steps involved.

To be specific, my Raspberry Pi is going to use my gmail account to send me email from the root user.  That means we will have to set up something on the Raspberry Pi and we will need to set up something on Google.

Lets start with

Google

You will need to set up an application sign-in for your Google account.  This is part of a security feature, that will generate an application specific password.  More information on it is here.

This is a summary of the instructions:

google_email

First visit your App Passwords page.

If you already have some Apps with passwords you will see them here.  But you will most likely need to generate a new one.

app_passwords

Generate a new application and password, but clicking on the Select app dropdown menu.  I usually select ‘Other’ and write in a name.  That will create a new password and it will look like this (I have, obviously, obscured the password).

generate_password

You will need to copy that password, and use it in the steps we do on the Raspberry Pi.

Raspberry Pi

On the Pi you will need to download a few things.

sudo apt-get install ssmtp
sudo apt-get install mailutils
sudo apt-get install mpack

These three installations will give your Pi the ability to act as an email server.  The last one ‘mpack’ will give you the opportunity to send attachments.

Once this is done, you will need to make changes to a file.

sudo nano /etc/ssmtp/ssmtp.conf

When you open this file with nano, you need to add these lines to the bottom, making changes where necessary.

root=youremail@gmail.com
mailhub=smtp.gmail.com:587
FromLineOverride=YES
AuthUser=youremail@gmail.com
AuthPass=yourgoogleapppassword
UseSTARTTLS=YES
USETLS=YES

To send an email from the terminal use the following command:

echo "sample text" | mail -s "Subject" username@domain.tld

The recipient will get an email from <root> using your gmail email address.  The subject will be “Subject” and the text of the email will be “sample text”.

This is pretty configurable, so you can add a lot of things.  A Google search on SSMTP will return a lot of resources.  I have a project that sends me an email once a day letting me know that something was completed or has failed.  It is also one of the friendlier emails I get all day.

Leave a Reply

Your email address will not be published. Required fields are marked *