Menu

Languages
Back to blog

Postfix

Delete messages from Postfix queue by sender address and recipient domain

Sorin PohonțuSorin Pohonțu
Delete messages from Postfix queue by sender address and recipient domain

Ever wanted to delete all messages from Postfix queue by sender email address and recipient domain ?

Today, I did … and below you can find a handful script for this purpose.

Tools needed: grep, awk, mailq and postsuper.

In a hurry ? Here is the core version:

mailq | tail -n +2 | head -n -2 | grep -v '^ *(' | awk 'BEGIN { RS = "" } { if (($7 == "sender@example.com") && ($8 ~ "somedomain.com")) print $1 }' | tr -d '*!' | postsuper -d -

And a little bit more elaborate version of the script, with parameters check and user confirmation:

#!/bin/bash

if [ "$#" -eq 0 ]
  then
	echo "No arguments supplied"
	echo "Usage: $0 sender@example.com somedomain.com" >&2
	exit 1
fi

read -p "Do you want to delete all queued messages from $1 to $2 ? " -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
	echo -e "Postfix Warning: Deleting all queued messages from $1 to $2"
	mailq | tail -n +2 | head -n -2 | grep -v '^ *(' | awk -v sender="$1" -v domain="$2" 'BEGIN { RS = "" } { if (($7 == sender) && ($8 ~ domain)) print $1 }' | tr -d '*!' | postsuper -d -
	echo "Operation completed ..."
else
	echo "Operation aborted ..."
fi

Detailed info ?

Typically, a mailq output looks like (eg, for Yahoo):

D7DA368BDDB    42143 Mon Oct 20 02:12:33  sender@example.com
(delivery temporarily suspended: lost connection with mta6.am0.yahoodns.net[63.250.192.45] while sending RCPT TO)
                                         recipient@yahoo.com

We’ll need to strip the second info line (mailq | tail -n +2), pipe the output to awk, set awk records separator to space and get the variables:

$1 = MessageID (D7DA368BDDB)

$7 = sender (sender@example.com)

$8 = recipient (recipient@yahoo.com)

In next step we’ll check if sender is our email address

($7 == "sender@example.com")

and the recipient domain contains our domain

($8 ~ "somedomain.com")

If all conditions are met, print $1 (MessageID) and pipe it to postsuper for deletion.

Bonus: Delete all MAILER-DAEMON notifications from Postfix queue:

mailq | tail -n +2 | head -n -2 | grep -v '^ *(' | awk 'BEGIN { RS = "" } { if ($7 == "MAILER-DAEMON") print $1 }' | tr -d '*!' | postsuper -d -

Notes:

  • Be careful when using this script on a live server. It will delete the messages matching the desired criteria from Postfix queue.
  • Script might be extended with additional features (like checking if sender email address and recipient domain are both valid).

Have fun :)

linuxpostfixmta