How to remove mail from postqueue based on email address

To delete a mail from postfix, i will usually run 2 commands below :
1) Postqueue -p (to list the postfix mail queue)
2) Postsuper -d "mail id" (to delete a mail based on id)

This method is easy if just need to delete few mails. How if there are bunch of messages queued in postfix. I was told by my superior to delete hundreds of mails queued in our mail server. Postfix does not have the function for doing that, luckily a search on Google gave a perl script for doing the clean up. All the credit goes to the site where i found the solution.

Here is a simple perl script that i found to delete my mails in postqueue.

1) Create a file (eg:delete_queue.pl) and paste the scripts below
2) chmod a+x delete_queue.pl
3) ./delete_queue.pl "mail id" (Delete mail based on mail id)
4) ./delete_queue.p "email address" (Delete mails from the same email address)

#!/usr/bin/perl -w
#
# pfdel - deletes message containing specified address from
# Postfix queue. Matches either sender or recipient address.
#
# Usage: pfdel
#

use strict;

# Change these paths if necessary.
my $LISTQ = "/usr/sbin/postqueue -p";
my $POSTSUPER = "/usr/sbin/postsuper";

my $email_addr = "";
my $qid = "";
my $euid = $>;

if ( @ARGV != 1 ) {
die "Usage: pfdel \n";
} else {
$email_addr = $ARGV[0];
}

if ( $euid != 0 ) {
die "You must be root to delete queue files.\n";
}


open(QUEUE, "$LISTQ |") ||
die "Can't get pipe to $LISTQ: $!\n";

my $entry = ; # skip single header line
$/ = ""; # Rest of queue entries print on
# multiple lines.
while ( $entry = ) {
if ( $entry =~ / $email_addr$/m ) {
($qid) = split(/\s+/, $entry, 2);
$qid =~ s/[\*\!]//;
next unless ($qid);

#
# Execute postsuper -d with the queue id.
# postsuper provides feedback when it deletes
# messages. Let its output go through.
#
if ( system($POSTSUPER, "-d", $qid) != 0 ) {
# If postsuper has a problem, bail.
die "Error executing $POSTSUPER: error " .
"code " . ($?/256) . "\n";
}
}
}
close(QUEUE);

if (! $qid ) {
die "No messages with the address <$email_addr> " .
"found in queue.\n";
}

exit 0;



0 comments: