Tutorial: Sending mail from the Linux command line via ssmtp and gmail

Sending mail from the command line can be useful in a lot of ways. Whether you quickly want to extract info from your operating system or use it in a bash script, it has proven to be a valuable asset in every system administrators toolbox.

To send email we need a smtp server and a Mail Transfer Agent (MTA). The two most well known and powerful MTAs are exim and postfix. However, many users won’t need the powerful features provided by those tools. In this article, we’ll use a MTA that is very easy to install and configure – SSMTP. We’ll also make use of gmail, one of the most well known free email providers.

To start things off, we’ll install ssmtp:

CentOS/RHEL:

# yum install ssmtp

Ubuntu/Debian:

apt-get install ssmtp

ssmtp’s configuration files are located in /etc/ssmtp/ for both distributions and consist of two configuration files: revaliases and ssmtp.conf. Note that you will need administrator privileges to cd into /etc/ssmtp.

ssmtp.conf is where the main configuration for ssmtp is located. revaliases stands for reverse aliases maps linux users to mail addresses.

To use gmail with ssmtp, we have to create an app password. An app password is a special password to your e-mail account which is only viable for a single application and will therefore not need two factor authentication. It’s a very simple process, but in case further help is needed, google provides very explicit instructions for gmail.

Now we can configure ssmtp.

Example configuration:

root=<user>@gmail.com
mailhub=smtp.gmail.com:587
AuthUser=<user>@gmail.com
AuthPass=<app password>
UseTLS=YES
UseSTARTTLS=YES

Replace <user> with your username and <app password> with the app password you generated.

Now you should be able to send mail using the command

# mail -s "<subject" recpient@mail.com <<< "<message body>"

In /etc/ssmtp/revaliases we can configure which address will be specified in the ‘From:’ field of our outbound mail.

Example:

root:username@gmail.com:smtp.gmail.com:587

would set the ‘From:’ field in all mails sent by root to username@gmail.com. This can be useful if you have multiple users on your system sending mail and you want to use different ‘From:’ addresses. Note that due to how smtp works, these addresses need not exist necessarily.

If you want to use ssmtp in bash scripts, here’s a very simple function I created:

function sendMail {
  mail -s "$subject" $recipient <<< "$body"
}

Note that you should put your parameters in hyphens if they contain blanks.

…and that’s it! Now it’s very easy to monitor various aspects of your system and be alerted by mail.

Leave a Reply

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

Archives