Sending Email Alerts Through Cron
Last Updated: Thu, Jul 2, 2009Cron is the Linux task scheduler that is responsible for making sure scripts run at their specified times. Cron is often used for things like, log rotation, backup scripts, updating file indexes, and running custom scripts. In the event a task runs into problems or errors Cron generally tries to email the local administrator of the machine. This means it tries to send an email to itself instead of an “internet accessible” email address like, ‘[email protected]’.
We can change this default behavior by changing the MAILTO variable.
Note: This will not work if you have not setup an email server.
Setting the MAILTO variable
Cron relies on a simple text file to schedule commands. To edit this file just issue the crontab command:
crontab -e
To change the MAILTO variable just add ‘[email protected]’ into the crontab file.
It should look something like this:
Specify Email for Each Script
If we don’t want all output to go to the same email address we can specify the output of a particular script to go to a different email address:
59 */6 * * * script.sh | mail -s "Subject of Mail" [email protected]
Email Alerts for All but One
If you have a specific script in your crontab that you don’t want output or errors emailed to you, simply add, ‘>/dev/null 2>&1’ to the end of the command.
59 */6 * * * script.sh >/dev/null 2>&1
To find out what else you can do with cron check out, Learning Cron by Example.
Cron Monitoring for Small Businesses that like to Self-Host
If you run a small business and want to centralize your logging and monitoring. I created a centralized logging system that is easy to self-host called Central Logging. Checkout the cron monitor docs.