May 25, 2019

BASH :: A quick script to help you search Postfix logs

(Last Updated On: 16th September 2016)

Have you ever has to grep through mail logs on Postfix?  What you quickly find is there are two problems which quickly become really irritating:

  1. You grep based on email address and so only get the lines relevant to that email address.  Sounds obvious but that means if you search for a sender, you won’t get the recipient in your output or if it has been delivered.  At this point you have to grep for the Message Queue ID to get all the relevant information for that message.  That means we are now doing 2 greps per email and it might not even be the right email!
  2. Message Queue IDs are randomised but can be reused, so searching a Message Queue ID can be a pain with big log files.

To make the process quicker and easier, I created a short BASH script that will loop through all the mail logs and return the relevant emails in an easy to read format.  The script will also display the message subject if you have enabled subject recording within the Postfix config.  For a guide on how to do that look here.

To use the script, copy and paste it into a file called  Once you have done that we need to give the script execute permission with the following command.

chmod +x

You are then ready to run it with the command ./

if [ $# -ne 1 ]
echo -e "\r\n\r\nWelcome to CheckMail!\r\n|\tI use a rather simple script to search the mail logs for a string\r\n|\tand then return the To and From fields from any matching emails"
echo -e "|\r\n|\t + Generally you would supply the email address i.e."
echo -e "|\t\t ./ '[email protected]'"
echo -e "|\t + but you can provide whatever you want to search for, such as Message ID or Date!"
echo -e "|\t\t ./ 'May 23' <<< Needs to be that format!"
echo -e "|\t\t ./ 'May  3' <<< 2 spaces for single digit days!"
echo -e "|\t\t ./ 'May 23.*[email protected]' <<< You can use wildcards!"
echo -e "|\r\nHave fun but remember, you must quote around spaces!\r\n\r\n"
exit 0
for log in `ls /var/log/mail*`
for x in `cat $log | grep "$1" -I | grep -E "\:\ ([0-9A-Z]{12})" -o | grep -o -E "[0-9A-Z]{12}" | sort -u`
echo "Begin Message Queue ID - $x -------"
cat $log | grep "$1" -C 50 | grep $x | grep -P "((to|from)=<[^\ ]*>|Subject:.*(?= from [a-zA-Z0-9\.]*\[([0-9][0-9]?[0-9]?\.){3})|[A-Z][a-z]{2}\ \ ?[0-9][0-9]?\ [0-2][0-9]\:[0-5][0-9](?=\:[0-5][0-9]))" -o | sort -u
echo "End of Message Queue ID - $x -------"
echo "--------"


I hope you find it useful,


NOTE: This requires uncompressed log files, not tar or gzip.

Previous «
Next »

Simon is a sysadmin for a global financial organisation and specialises in Windows, security and automation.

Leave a Reply

Subscribe to SYNACK via Email

%d bloggers like this: