1. Overview

Cron and Crontab are related concepts but serve different purposes and are used in slightly different contexts. Cron is the scheduling service that runs tasks at specific times, while Crontab is the user-friendly interface for configuring and managing those scheduled tasks within the Cron system. It’s important to configure email notifications for these tasks so that we’re aware of their status and can take action if necessary.

In this article, we’ll learn how to configure email notifications for crontab on Linux systems.

2. Crontab and the Need for Email Notifications

Crontab is a file that schedules tasks on Linux systems (Linux, macOS, BSD). Users create their own crontabs with scheduled jobs and corresponding run times.

Each entry in a crontab file consists of fields representing the minute, hour, day of the month, month, and day of the week, each with values or symbols denoting when a task should run. These fields are combined to create a schedule that can be as simple as running a script daily at a specific time or as complex as executing multiple tasks at various intervals.

When we schedule tasks in crontab, it’s important to receive notifications about their execution status. Email notifications are a common way to achieve this. By configuring email alerts for our cron jobs, we can:

  • Stay Informed: It enables us to receive updates on the success or failure of our scheduled tasks.
  • Take Prompt Action: It helps quickly address any issues or errors in our scripts or scheduled tasks.
  • Monitor System Health: It ensures that critical system maintenance tasks are executed as expected.
  • Reduce Downtime: It minimizes the impact of failures by addressing them promptly.

3. Steps to Configure Email Notifications

This guide will walk us through the essential steps required to configure email notifications effectively. By the end of this process, we’ll have a streamlined system that not only automates tasks but also keeps us informed about their execution, errors, and important outcomes. Now, let’s delve into the steps to configure email notifications for crontab.

3.1. Verifying Email Configuration

Before setting up a crontab for email notifications, it’s important to ensure that the system allows sending emails. To do this, we need to have a mail transfer agent (MTA) like Sendmail or Postfix installed and configured. 

Let’s take a look at how to install and configure Sendmail:

$ sudo apt update
$ sudo apt install sendmail

Once installed, we need to follow the on-screen prompts for its configuration.

If we prefer Postfix as the MTA, let’s see how to install it:

$ sudo apt update
$ sudo apt install postfix

During the installation of Postfix, we’ll be prompted to choose the server configuration type. For most cases, we can select “Internet Site” and enter the system’s mail name. To reconfigure Postfix, we’ll use the following command:

$ sudo dpkg-reconfigure postfix

We can send a test email from the command line to verify if our email configuration is correct. For instance, we’ll use the mail command to send a test email:

$ echo "This is a test email" | mail -s "Test Email" [email protected]

If we receive the test email successfully, then our email setup is working fine. If not, we may need to troubleshoot the MTA configuration.

3.2. Editing Crontab File

In order to set up email notifications for a particular cron job, we’ll need to modify the crontab file. To do this, we can edit the crontab file by executing the following command: 

$ crontab -e

This command will open the crontab file in the default text editor specified by the EDITOR environment variable.

3.3. Configuring Email Notifications

If we wish to receive email notifications for a specific cron job, we can redirect the output of the command to an email address. This includes both the standard output and the standard error. To specify the recipient’s email address and the email’s destination, we can define the MAILTO variable in crontab. The basic syntax to configure email notifications in crontab is:

MAILTO="[email protected]"

In this example, we’ll have to replace [email protected] with the actual email address.

3.4. Verifying Configuration

To check if our email notifications are set up correctly, we can add a test cron job that executes a simple command and sends an email:

* * * * * echo "Cron job test" >> /dev/null

This cron job will run every minute and append the message “Cron job test” to the email output.

After waiting for a minute or two, an email will be sent to the address specified in the MAILTO variable.

4. Optimizing Crontab Email Alerts

Efficiently managing our cron jobs involves more than just scheduling tasks. It entails crafting a streamlined notification system to keep stakeholders informed about the execution and outcomes of these automated processes. From redirecting output to email and extending communication to multiple recipients, to customizing subjects for better context. This will aim to elevate our crontab email alerts to a new level of effectiveness and precision. Here are some additional tips that will unravel the intricacies of these optimization techniques.

4.1. Redirecting Output to Email

To receive email notifications for the output of a cron job, we must use the >> operator to add the output to an email message:

# Test cron job: run every minute and append output to a file
* * * * * echo "Cron job test" >> /tmp/cron_test_output.log 2>&1

After the cron job runs, the contents of /tmp/cron_test_output.log will include the output of the command. Now, to send the contents of this file in an email, we can use the mail command:

mail -s "Cron Test Output" $MAILTO < /tmp/cron_test_output.log

If we want to suppress the output, we can use >> /dev/null 2>&1 to suppress both stdout and stderr:

* * * * * /path/to/your-script.sh >>/dev/null 2>&1

Alternatively, we can use 2> /dev/null to suppress only stderr or 1> /dev/null or > /dev/null to suppress only stdout:

0 1 * * * /path/to/your/script.sh 2> /dev/null
0 1 * * * /path/to/your/script.sh 1> /dev/null
# or
0 1 * * * /path/to/your/script.sh > /dev/null

After configuring email notifications for our cron job, we need to save the crontab file and exit the text editor:

  • In vi, press Esc, then type:wq and press Enter.
  • In nano, press Ctrl + O to save and Ctrl + X to exit.

4.2. E-Mail to More Than One Person

When we want to send an email to more than one person, we must separate the email addresses with commas in the MAILTO variable. This allows the cron job’s output, including any errors, to be sent to all specified email addresses. Let’s illustrate this with an example:

MAILTO="[email protected], [email protected], [email protected]"
* * * * * /path/to/our/script.sh

This approach allows us to include multiple recipients in the email notifications. It ensures that all designated individuals receive relevant information about the cron job’s execution.

An exception to this case occurs when we need to send email notifications for cron jobs to a specific email address. In order to do so, we must include the MAILTO line before each job entry in our crontab file. By setting the MAILTO variable before individual job definitions, we designate the recipient for notifications related to each specific task. Let’s illustrate this with an example:

MAILTO="[email protected]"
* * * * * /path/to/our/first_script.sh

MAILTO="[email protected]"
0 2 * * * /path/to/our/second_script.sh

MAILTO="[email protected]"
15 4 * * * /path/to/our/third_script.sh

4.3. Subject Customization

When we want to customize the subject of our cron job emails, we must use the -s option with the mail command. This allows us to provide a specific subject line for each email notification. Let’s explore this with an example:

# /path/to/our/script.sh
# Perform script tasks...
# Send email with a custom subject
echo "This is the body of the email." | mail -s "Custom Subject for Cron Job" "$MAILTO"

This practice will allow us to provide more context or specific information in the subject line, making it easier to identify the purpose of the email notification.

5. Conclusion

In this tutorial, we discussed how configuring email notifications for crontab is an essential practice for system administrators and anyone who relies on scheduled tasks for automation.

We learned how to set strategies such as redirecting output to email, extending communication to multiple recipients, and customizing subjects. We’ve gained valuable insights into enhancing the effectiveness and precision of our crontab email alerts. This proactive approach ensures that we receive timely notifications about the execution status of our cron jobs.

What we saw, allows us to maintain the health of our systems and promptly address any issues that may arise, ultimately saving our time and effort in the long run.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.