Send Mail from your Raspberry Pi

I have to go searching for how to do this every time. This time I thought I would memorialize the instructions. I found this in an article written by Stacy Prowell on Medium.com.

The first thing you need is some additional software. I am going to use Postfix, which is a mail transfer agent (MTA) — that is, something that knows how to talk to other MTAs to send and receive email. In particular, Postfix supports the simple mail transfer protocol (SMTP), so it can talk to nearly any other MTA out there, including Google’s Gmail. In case you don’t like Gmail, there are guides online like this one for getting Postfix to talk to other SMTP servers.

1. Install Postfix

Run the following command at the prompt to install Postfix along with simple authentication layer security (SASL), which Postfix will use to connect to Gmail.

sudo apt install postfix libsasl2-modules

During the installation, you will be asked about how the mail server should operate. You want an Internet Site, where email is sent and received directly using SMTP, so select that option.

Screenshot of package configuration screen
So many choices

Now you’ll be asked for the “system mail name.” You should use your hostname (raspberrypi, for instance) or, if you have a fully-qualified domain name for your network via your ISP or a service like DYN, then you can use that. Don’t stress over this; you can modify it later by editing the /etc/postfix/main.cf file if you need to.

Screenshot of a package configuration dialog
Set the server name

2. Get an Application Password for Postfix from Google

have Google set up for two-factor authentication (2FA), so how will the Pi be able to send an email? Well, it turns out you can get Google to generate an application password, which is a password to allow a specific application to connect.

To get an application password head to: https://myaccount.google.com and log in.

Screenshot of Google account options
Account security settings

Select “Security” from the list on the left.

Screenshot of Google account security options
Manage your application passwords

Note that I have two-step verification turned on. You might or might not; either way, creating an application password for each application is a good idea. If you lose a device or it is stolen, you can revoke the application password and not have to change your existing password or passwords for other applications.

There should be a box for “Signing in to Google” that contains an option for “App passwords.” Click on that. You might have to sign in again at this point (I did). This should take you to the page to manage application passwords. The example account I am using doesn’t have any.

Screenshot of app password manager
Create a new application password

Now click on “Select app” and select Mail. Then click on “Select device” and select Other. You’ll need to enter the name of the device (for this example it is raspberrypi4). Click Generate to create the application password.

Screenshot of new application password
A new application password! Don’t get excited; I’ve already deleted it.

You should now be presented with a new application password. This is the text in the yellow block in the image above. Success! Do not click done! Copy the app password first, or write it down. You’ll need it and you can’t display it again.

3. Configure SASL

(A lot of the content of this section is taken from the Postfix SASL HowTo.)

We are almost done. The next thing to do is to add the app password you just generated to the SASL configuration. Run the following command.

sudo nano -B /etc/postfix/sasl/sasl_passwd

This command will open the file in an editor. It is likely the file does not exist, and you will see an empty file. Add the following line, replacing username and password with your Gmail username and the application password you just generated (don’t include the spaces).

[smtp.gmail.com]:587 username@gmail.com:password

This line tells SASL that when it connects to the host smtp.gmail.com at port 587 to download mail, it should use the given username and password to connect. Exit and save with CTRL+x, y, and Enter.

This file contains a “clear text” password. Run the following command to protect that file.

sudo chmod u=rw,go= /etc/postfix/sasl/sasl_passwd

This command sets the user permissions (root) to read and write and removes any permissions for the group and others. (Fans of the numerical form of chmod will recognize this as 0600.)

Now turn this file into a hash file for Postfix. Run the following command.

sudo postmap /etc/postfix/sasl/sasl_passwd

This command will create a new file named sasl_passwd.db in the same directory. It should already have the permissions set correctly, but just in case, let’s also explicitly set the permissions.

sudo chmod u=rw,go= /etc/postfix/sasl/sasl_passwd.db

4. Configure Postfix

Now let’s finish up the configuration of Postfix. Run the following commands.

sudo cp /etc/postfix/main.cf !#$.dist
sudo nano /etc/postfix/main.cf

Find the line (near the bottom) that starts with relayhost =. Here is where we specify that we want to use Google’s SMTP server as our relay host, and this must match what we put in /etc/postfix/sasl/sasl_passwd. Change the line so it looks as follows.

relayhost = [smtp.gmail.com]:587

Next, add the following to the end of the file. (Documentation for these options and others can be found here.)

# Enable authentication using SASL.
smtp_sasl_auth_enable = yes
# Use transport layer security (TLS) encryption.
smtp_tls_security_level = encrypt
# Do not allow anonymous authentication.
smtp_sasl_security_options = noanonymous
# Specify where to find the login information.
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
# Where to find the certificate authority (CA) certificates.
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Save and exit with CTRL+x, y, and Enter, and then restart Postfix with the following command.

sudo systemctl restart postfix

5. Testing Email

Next, let’s verify that we can send an email via Google’s SMTP server. Type the following at the command line, replacing username with your Gmail user name (so the email goes to you).

sendmail username@gmail.com
Subject: It works!
Hey, it works!
.

The first line uses the sendmail command to send an email to the specified recipients (you can list more than one). The subsequent lines optionally specify mail headers like the subject, and then the body of the email. The entire thing is terminated by a period. Note that this is just one way to send email using the sendmail command. Later we will use sendmail to send the output of commands.

Check your email. If you got an email from yourself (remember: Postfix is using your credentials) then everything is working. If you didn’t, then you should check a few places on the system.

Checking for Problems

The most obvious problems are an inability to reach the Gmail server and a failure to authenticate with the Gmail server.

Inability to reach the Gmail SMTP servers

Make sure the network is connected and see if you can reach the Gmail SMTP server. The easiest way to do this is to “ping” smtp.gmail.com. If you see a failure message like “ping: smtp.gmail.com: Name or service not known,” then you should check your network connectivity. (It is possible that your ISP or the Google service itself is down… but this is less likely.)

Failure to authenticate with the Gmail SMTP servers

To see this, check the file /var/log/syslog for messages from postfix. If you see a message like the one below, your credentials were not accepted.

Dec 10 08:04:01 raspberrypi postfix/smtp[18329]: 331F960582: SASL authentication failed; server smtp.gmail.com[108.177.122.108] said: 535-5.7.8 Username and Password not accepted. Learn more at?535 5.7.8  https://support.google.com/mail/?p=BadCredentials c188sm1372198ywb.56 - gsmtp

Check that the content of /etc/postfix/sasl/sasl_passwd is exactly what it should be, and make sure you ran the postmap command to create the hash file. If everything looks correct, or if you don’t have your application password written down, go back to Google account management and delete the old application password, create a new one, and carefully add it to /etc/postfix/sasl/sasl_passwd and then run the postmap command given earlier.

Adding Email Aliases

You can add email aliases by editing the file /etc/aliases and then running the newaliases command. This can be used to tell Postfix how to handle local email addresses.

For example, perhaps you want email to the pi user to go to your Gmail account. You would run the following command to edit the aliases file.

sudo nano -R /etc/aliases

Next, you would add the following line, where username is your Gmail username.

pi: username@gmail.com

Finally, tell the system about the new mail aliases by running the following command.

sudo newaliases

Now mail sent to pi will be forwarded along by Postfix to your Gmail account.

Depending on what you are using the Pi for, you might forward postmaster, webmaster, or other names. Note that these don’t have to correspond to any local account.

Sending Text Messages

A computer in our server room sends me a text message each morning using a dedicated cellular long term evolution (LTE) modem. The Pi doesn’t have one (though you can buy them; for instance, here’s one), but if you’ve successfully followed the above instructions, your Pi can send email, and it turns out you can send a text message by first sending an email.

First, a word of warning. Sending an email over a connection to Gmail isn’t likely to cost you any more than you are already paying for internet connectivity. But receiving a text message on your phone just might. Check your plans, and be courteous of other people who might not want unsolicited text messages from you.

Email to Text

Cellular providers will convert emails sent to a special address into text messages, and forward them along. Text replies may be converted back to a return email, but this is less certain. The two articles below cover this in some detail and provide information for both short message service (SMS) and multimedia message service (MMS), where supported.

Here are the top four North American providers and the information for each. (Apologies to non-North American readers; there are far too many wireless services around the world for me to try to include them all.)

Service Name SMS Email Suffix MMS Email Suffix
AT&T Mobility @txt.att.net @mms.att.net
Verizon Wireless @vtext.com @vzwpix.com
T-Mobile @tmomail.net @tmomail.net (same)
Sprint Corporation @messaging.sprintpcs.com @pm.sprint.com
view raw email-to-text.csv hosted with ❤ by GitHub

You use these by finding the provider for the recipient of the message, and then sending an email to the ten-digit (North American) phone number followed by the appropriate email suffix.

For instance, suppose your cell phone number is (724) 555–1212, and your provider is Verizon. Then you can send yourself a text by sending an email message to the address 7245551212@vtext.com. These SMS messages are typically limited to 140 characters.

You can also send MMS messages, but this is a bit more complex.

Email to Text from the Raspberry Pi

My carrier is Sprint, and my number is (not really) 724–555–1212. So to send a text to my phone I can send a short text email to 7245551212@messaging.sprintpcs.com. Let’s try a test.

At the prompt of the Raspberry Pi, try the following (replacing the address with whatever is correct for your cell phone).

echo "Test" | sendmail 7245551212@messaging.sprintpcs.com

You should receive a text on your phone.

Screenshot of a text message
Success!

Great! If you don’t, check your Gmail for a delivery failure notice, and make sure you are using the correct address for the recipient (you, in this case).

Reply to Text

What happens if you reply to a text? Well, that depends on your service provider. For my provider (Sprint) an email is created and sent.

Reply email
Talking back to the text

You can reply to this email, and the result will be a (possibly very ugly) text message. Communication achieved!

Note that if you are getting your hopes up on automatically processing the replies, you should be careful. The reply above was sent as a base 64 encoded rich text file. That is, you may have to do some work if you want true two-way communication.

Things to Say

Now that you can send email and text messages from the Pi, what should the Pi say? Well, as mentioned at the start, I set my Pi up to be a file server, and so one thing I would like is a report on the file system usage each morning when I get up. I’m also mildly paranoid, so I’d like to know when someone logs into the Pi. One is almost trivial. The other requires a bit more work.

This would be a good time to add an alias for text messages. For example, you might add the following line to your /etc/aliases and then run sudo newaliases as described previously.

alert: 7245551212@messaging.sprintpcs.com

From now on you can just send email to alert, and Postfix will turn it into a text message to your phone.

Reporting File System Usage

I am using two drives to store information: /data/a and /data/b (I’m not that creative). I can check on the file system used with the following command.

df --output=target,pcent /data/a /data/b

(I only want to know about those two file systems; if I did not include them, the df command would list all the mounted file systems… which might be what you want in some cases.)

This tells me exactly what I want to know: how much space is used in each file system. If this space gets too high, I know I need to add more storage. This is the output from the above command as I write this.

Mounted on Use%
/data/a 3%
/data/b 2%

It’s short and simple, under 140 characters, and a perfect thing to text to me in the morning to let me know the status of my file server. I can drop the header line and send the output with the following command, using the alert alias we created at the start of this section.

df --output=target,pcent /data/a /data/b | \
tail +2 | /usr/sbin/sendmail alert
A screenshot of text messages
Success! Information you can ignore until it gets out of hand.

(The tail +2 tells the system to copy all output from the prior command, starting at the second line… so this skips the header line.)

Great! Now I want this to run as a command every morning at 6:00 am. For that, I will use the Linux cron utility.

Every user has a special file called the crontab that contains information on commands to execute, when, how often, etc. Do not edit this file directly! There is a special command, crontab, for examining and editing this file.

The following command will list the content of the user’s crontab file.

crontab -l

By default, each user gets a crontab file with a helpful usage message as a series of comments. You should leave these comments in for reference!

# Edit this file to introduce tasks to be run by cron.               
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command

Now let’s add a line to generate the file system usage message every morning at 6:00 am. Note that we want to run more than one command, so we need to enclose the whole thing in parentheses. If we were running a single command we would not need the parentheses.

To edit the crontab, run crontab -e. This will open your crontab in an editor. Add the following line, below the format comment, save, and exit.

# m h  dom mon dow   command
0 6 * * * ( df --output=target,pcent /data/a /data/b | tail +2 | /usr/sbin/sendmail alert )

The minutes (m) is zero, the hour (h) is 6 (using 24 hour time), we want every day of the month (dom), every month (mon), and every day of the week (dow), so we set those three to asterisks (*). Alternately, if I just wanted a report every Friday afternoon at 5:30 pm, I would write the following.

# m h  dom mon dow   command
30 17 * * FRI ( df --output=target,pcent /data/a /data/b | tail +2 | /usr/sbin/sendmail alert )

If this seems much too tricky, don’t lose hope. Head over to the Crontab Guru site for help. You can (and I do) have multiple lines in your crontab to do a variety of things. If you want to know more about how crontab works, the file format, etc., see Ranjan Bajracharya’s article on cron jobs.

Reporting SSH Logins

I have the Pi set up to allow remote logins using two-factor authentication. I wrote a short article on how to do that, too.

Setting Up SSH and 2FA on a Raspberry PiLog in from anywhere using SSH and Google Authenticatormedium.com

Because the Pi is accessible remotely, I’d like to be alerted when someone logs in via SSH. Doing that is pretty easy, it turns out. (Of course, this is only going to work is you have enabled SSH.)

First, create a new script. We’ll put this in the /etc folder.

sudo nano /etc/notify-ssh-login.sh

The content of the file should be as follows. (Note that this script depends on the alert alias created at the start of this section. It is a Really Good Idea to try to capture this sort of information in a single place and not scatter it around the system!)

#!/bin/bashPATH=/bin:/usr/bin:/usr/sbin
SUBJ="Alert - Remote SSH access from ${PAM_USER}"if [ -z "$PAM_TYPE" -o "$PAM_TYPE" == "open_session" ]
thensendmail alert <<END
$(hostname) $(date): LOGIN by ${PAM_USER} from ${PAM_RHOST}
$(who)
ENDelsesendmail alert <<END
$(hostname) $(date): LOG OUT by ${PAM_USER} from ${PAM_RHOST}
ENDfi

Next, we need to arrange for the Linux pluggable authentication module (PAM) system to invoke this script whenever someone logs in or logs out via an SSH session. Run the following command.

sudo nano -R /etc/pam.d/sshd

Let’s protect the file against changes.

sudo chmod go-w /etc/notify-ssh-login.sh

Add the following lines at the end of the file.

# Notify on successful login / log out.
session optional pam_exec.so /etc/notify-ssh-login.sh

Now log into the Pi via SSH and make sure you get a text message. You should get a shorter message when you log out.

Screenshot of text messages reporting login and log out
Watching log in and log out. The list of users in the first message includes the console user (tty1)

You can do a lot of other things with PAM; details are beyond this short document, but there are many excellent articles that cover this important system.