The Cron utility of emails the output and errors of an executed job to the appropriate Linux user. This requires a properly setup mail server such as sendmail.
However you can use msmtp (an SMTP client) to receive emails from cron jobs to each users’ preferred email ID through your preferred email provider.
Make sure msmtp is installed and configured by following the instructions here.
Method 1: msmtp for all cron jobs
By following this method you’ll be using msmtp system-wide for all cron jobs.
A few modifications to the
/etc/msmtprc file are required to make it work with crontab. First we need an aliases file so set its path in the msmtprc file.
This file should contain Linux usernames to email mappings like this.
root: email@example.com jesin: firstname.lastname@example.org default: email@example.com
default is the default email to which an email will be sent if no match for a user is found.
Next you need to set an account as default in the
/etc/msmtprc file. So add this line to the end
account default : provider
Check if you already have sendmail or a sendmail wrapper installed using the
If you get an output for this you should uninstall that package first using the
yum remove or
apt-get remove command.
Create a symbolic link for msmtp in the path used by sendmail.
ln -s /usr/bin/msmtp /usr/sbin/sendmail
Now test this from the command line using a Linux username as a recipient.
echo "From: root \ To: jesin \ Subject: Hello World \ \ This is the email body" | sudo sendmail -d -t jesin
-d option is to display detailed debugging information so that it is easier to troubleshoot if it doesn’t work as expected.
Create a cron job which echos some text which causes an email to be sent.
* * * * * echo "A message from Cron"
Have a look at your
messages file to know what is happening
tail -f /var/log/syslog
You’ll have to wait for 60 seconds for the cron job to execute.
Oct 31 07:38:50 localhost crontab: (jesin) LIST (jesin) Oct 31 07:38:51 localhost crontab: (jesin) BEGIN EDIT (jesin) Oct 31 07:39:40 localhost crontab: (jesin) REPLACE (jesin) Oct 31 07:39:40 localhost crontab: (jesin) END EDIT (jesin) Oct 31 07:40:01 localhost CRON: (jesin) CMD (echo "A message from Cron")
Make sure to remove the cron job immediately else an email will be triggered every minute and your Email Service provider might suspend your account.
Method 2: msmtp for specific cron jobs
If you need status emails only from specific cron jobs you can do so by simply redirecting the stdout and stderr messages.
* * * * * /scripts/backup.sh 2>&1 | msmtp firstname.lastname@example.org
2>&1 redirection operator sends both the stdout and stderr of backup.sh to msmtp which sends an email with this content in the email body.