Shell Bash Script to shut down qmail, when number of emails in queue exceeds user set limit

November 11, 2014

If you are running a linux server with qmail and Plesk, there is a big chance that you have faced the problem of having thousands of emails in a mail queue due to spam attacks. Here is small Shell/Bash script that you can place as a crontab job, that it will shut down qmail if the number of messages in queue gets over the set limit.

#!/bin/bash

#Declaring default values for the parameters
# MAX_Q_SZ - maximum number of messages in queue, when system will shut down qmail
MAX_Q_SZ=10

# PING_PAGE - URL of the page that server will ping. this page should send an email/SMS to sys admin with notification that qmail is shutting down
PING_PAGE="http://swslive.com/"

#Check if parameter with maximum emails value was passed into the file
if [ $# -gt 0 ]
then
        MAX_Q_SZ=$1
fi

#Check if parameter with URL was passed into the file
if [ $# -gt 1 ]
then
        PING_PAGE=$2
fi

#Following 2 lines are needed for separating output of the qmail stat.
OIFS=$IFS;
IFS=" ";

#Running qmail stat and saving output
VQ="/var/qmail/bin"
export PATH=$VQ:$PATH
QSZ=`qmail-qstat ./Maildir/ | head -n 1 | sed -e 's/.*: \(.*\)/\1/g'`

#Check if number of messages in queue are not exceeding maximum value
if [ $QSZ -gt $MAX_Q_SZ ]
then
        #Ping URL for the notification
        wget $PING_PAGE -O /dev/null

        #Shut down qmail
        service qmail stop
        exit
fi