How to Override MAILTO for a Single Crontab Entry: Targeted Email Notifications


2 views

html

In many team environments, system crontabs are configured with a global MAILTO directive that sends job failure notifications to a shared email address. While this works well for general monitoring, it becomes problematic when you need specific alerts for individual cron jobs.

The good news is you can override the global MAILTO for individual cron entries by setting the MAILTO environment variable directly in the command:

# Global MAILTO (shared team address)
MAILTO=team-alerts@example.com

# Individual job with custom notification
* * * * * MAILTO=your-email@example.com /path/to/your/script.sh

For more complex scenarios, you can pipe the command output to mail directly:

* * * * * /path/to/your/script.sh 2>&1 | mail -s "Cron Job Alert" your-email@example.com

Remember that cron only emails on non-zero exit codes. If you need to force notifications, ensure your script handles exit codes correctly:

#!/bin/bash
# Your script logic here

if [ $? -ne 0 ]; then
    echo "Error occurred" | mail -s "Script Failed" your-email@example.com
    exit 1
fi
  • Consider using a dedicated monitoring system for critical jobs
  • Implement proper logging in addition to email notifications
  • Use descriptive subject lines for easier triaging
  • Test your notification setup thoroughly

In enterprise environments, it's common to have role accounts with crontabs configured to send email notifications to a shared distribution list when jobs fail. While this ensures team visibility, there are cases where you might want specific jobs to notify only individual maintainers.

The standard crontab MAILTO directive sets the default recipient for all job outputs:

MAILTO=team-alerts@company.com
# Daily backup
0 2 * * * /usr/local/bin/backup.sh
# Weekly report
0 5 * * 1 /usr/local/bin/generate_reports.sh

You can override the default MAILTO for individual jobs by:

# Standard job using default MAILTO
0 3 * * * /path/to/script.sh

# Custom notification job
0 4 * * * /path/to/personal_script.sh || echo "Job failed" | mail -s "Cron Job Failure" dev@company.com

For better error handling and more control:

#!/bin/bash
# custom_cron_wrapper.sh
MAIL_RECIPIENT="your.email@company.com"
LOG_FILE="/var/log/custom_cron.log"

/path/to/actual_script.sh >> $LOG_FILE 2>&1
if [ $? -ne 0 ]; then
    echo "Script failed. Check logs at $LOG_FILE" | mail -s "Cron Failure Alert" $MAIL_RECIPIENT
fi

Then in crontab:

0 5 * * * /path/to/custom_cron_wrapper.sh

Another clean method using environment variables:

MAILTO=team-alerts@company.com

# Special job with custom notification
SPECIAL_MAILTO=dev@company.com * * * * /path/to/special_script.sh

When implementing custom notifications:

  • Ensure proper error handling in your scripts
  • Consider log rotation for wrapper scripts
  • Document overrides clearly in crontab comments
  • Test notification delivery mechanisms