Create a script to send you rejected emails

 

Overview

The following explains how to create a script to notify you if an email sent from your web server is blocked or rejected.

Background

If an email (sent from your web server) is blocked or rejected, it is stored in the following directory:

/home/username/Maildir/new

To view these emails, you can:

  • manually log into your server and check the files in this directory.
  • or create a cron job that runs a script that automatically emails you when an email is blocked or rejected.

See this article for more information about blocked or rejected emails.

Configuring the email script

The following steps create a shell script and cron job to notify you of rejected emails from your website.

 

Create a shell script (on the server)

  1. Log into your server via SSH.
  2. Make sure you're in your user's home directory:
    [server]$ cd ~
    [server]$ pwd
    /home/username
  3. Create a new file via SSH, and then name it something like mailrejections.sh.
  4. Add the following code to this file:
    #!/bin/bash
    
    #Check ~/Maildir/new for any files created within the last 15 min
    files=$(find ~/Maildir/new -type f -mmin -15)
    
    for emailFileName in $files; do
      #open each email individually and assign to new variable
      emailContent=$(cat $emailFileName)
    printf '%s\n' "${emailContent[*]}" | mail -s "These emails were rejected" admin@example.com done
    exit 0

    You only need to change the highlighted text.

    • You can change the message to anything you like. This will be the subject of the email you receive.
    • Update the email to an address on the website you're sending from.

Add a cron job (in the panel)

After you create the script, you must create a new cron job to run every 15 minutes. The cron job then runs the file you just created.

  1. Create a new cron job in your panel:
    Panel cron email rejection
  2. Make sure to adjust the username to the correct Shell user for which you created the script.
  3. Click the When to run dropdown menu and select Custom.
  4. Select 'Every 15 minutes' for the time frame.

    You can change the time frame to anything you like, but just make sure to update the same time frame in your script to match.

  5. Click the Add button to save.

The cron job runs your script every 15 minutes. If an email is rejected, a copy of it is then sent to the address you specified in the script.

Create a mail filter

This step is optional but recommended to ensure you receive any incoming emails from your server. Just create a filter to move incoming emails with the subject line (in your script) to a new folder in your mail client. 

You can create the filter within your email client or by creating a custom filter in the panel

See also

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?