Automatic cleanup of frozen messages in Exim

In my previous post I described how to deal with frozen messages. However eg. on an application server with a huge number of mails sent out on a daily basis you can get hundreds of frozen messages every day due to invalid recipient addresses, etc. In this case you need an automatized way to deal with them.

I've found a nicely written script in the archives of the exim-users mailing list. It was not made for use in a cron job, so I modified it like this:
#!/bin/sh

exim -bpru | awk '
BEGIN {
  rmfunct = "exim -Mrm ";
  rmlist = "";
  num = 0;
}
/^ *[0-9]+[a-z].*\*\*\* *frozen *\*\*\*$/ {
  rmlist = rmlist " " $3;
  ++num;
  if (num >= 50) {
    if (system(rmfunct rmlist " > /dev/null") != 0) {
      print "Call to " rmfunct " " rmlist " failed.";
    }
    rmlist = "";
    num = 0;
  }
}
END {
  if (num > 0) {
    if (system(rmfunct rmlist " > /dev/null") != 0) {
      print "Call to " rmfunct " " rmlist " failed.";
    }
  }
}'

It's pretty simple and effective. Copy the above code into a text file (eg. ~root/bin/exim_cleanup.sh), assign execute privilege to the script (chmod 0700 ~root/bin/exim_cleanup.sh) and add the following line to the end of the root user's crontab file:
0 0 * * * ${HOME}/bin/exim_cleanup.sh

If the script produces any errors (which it shouldn't Smile), then the root account will get a mail with the output of the cron job.