Linux – How to get e-mail from (failed) cron-jobs in Ubuntu

cronemaillinuxUbuntuunix

I create cron-jobs in Ubuntu by placing the executable in one of /etc/cron.{daily,hourly,monthly,weekly}. There are lots of directories starting with cron:

kent@rat:~$ ls -ld /etc/cron*
drwxr-xr-x 2 root root 4096 2009-06-06 18:52 /etc/cron.d
drwxr-xr-x 2 root root 4096 2009-07-16 13:17 /etc/cron.daily
drwxr-xr-x 2 root root 4096 2009-06-06 18:52 /etc/cron.hourly
drwxr-xr-x 2 root root 4096 2009-06-06 18:52 /etc/cron.monthly
-rw-r--r-- 1 root root  724 2009-05-16 23:49 /etc/crontab
drwxr-xr-x 2 root root 4096 2009-06-06 18:52 /etc/cron.weekly

I would like to get e-mail from my scripts when:

  1. A script fails and gives an exit code of non-zero.
  2. The script has something to tell me

I have SSMTP installed and working, I send my mail from my Google-account. The fact that SSMTP can only send mail using one account isn't a problem for me. It's just a home server and the users I have do not have the ability to add cron-jobs.

I would like to know how the mailing from scripts usually works in Linux/Unix in general and in Ubuntu specifically. I would also like to know of a good way for me to get mails in the two situations above.

Best Answer

By default, cron will email the owner of the account under which the crontab is running.

The system-wide crontab is in /etc/crontab runs under the user `root'

Because root is used widely, I'd recommend adding a root alias to your /etc/aliases file anyways. (run 'newaliases' after)

The normal way to structure this is for root to be aliased to another user on the system, e.g. for me I'd alias 'root' to 'phil' (my user account) and alias 'phil' to my external email address.

If you have a specific user cron that you'd like emailed to you on output, you can use /etc/aliases again (providing you have superuser access) to redirect the user to another email address, or you can use the following at the top of your crontab:

MAILTO="email@domain.com"

If mail should be sent to a local user, you may put just the username instead:

MAILTO=someuser

If you need more information see crontab(5) by running:

man 5 crontab
Related Topic