Introduction
In this tutorial you will learn how to set up sSMTP in order to receive email notifications from your server. This makes it possible to get the output of a cron job via email.
Prerequisites
- An email account that will send the emails.
Step 1 - Install sSMTP
Connect to your server via SSH, and install sSMTP. You can do that by running:
apt update
apt install ssmtp
Step 2 - Update the sSMTP Configuration
The configuration files of sSMTP can be found under /etc/ssmtp
.
Adjust settings in the /etc/ssmtp/ssmtp.conf
file.
When you are done, it should look like this:
MailHub=<smtp.example.com:465>
AuthUser=<cron-sender@example.com>
AuthPass=<cron-sender password>
UseTLS=YES
FromLineOverride=YES
Step 3 - Setup a Cron Job
Now you can setup a cron job with crontab -e
.
Before your cron jobs, you have to add MAILTO=<my-address@example.com>
and MAILFROM=<cron-sender@example.com>
.
MAILTO=<my-address@example.com>
MAILFROM=<cron-sender@example.com>
* * * * * echo 'Hello from cron'
Now you will get an email whenever a cron job runs.
Step 4 - Exclude a Cron Job from Sending Email
If you don't want a cron job to send emails, you can simply add >/dev/null 2>&1
at the end.
This will redirect both stdout and stderr of that job to /dev/null
and no email will be sent.
MAILTO=<my-address@example.com>
MAILFROM=<cron-sender@example.com>
* * * * * echo 'This text will be sent to /dev/null' >/dev/null 2>&1
Conclusion
With sSMTP configured on your server, you will now get emails for every cron job. This can be super helpful for example if you are auto upgrading some services on your machine. However, it can also be annoying. If you have a cron job that runs every minute, for example, you will also get an email every minute, so make sure you carefully select which cron jobs will send emails.