Friday 11 December 2009

Bulk delete from Postfix queue

To delete a message in Postfix queue, I normally find out the message id first from “postqueue -p” (or simply “mailq”) command. Once the message id is known, I simply issue the following command to delete that particular message (assume the message id is BA4491827DE):

# postsuper -d BA4491827DE

If there is only one message to delete, I can live with that. However, when there’s a bunch of messages (e.g. from a particular domain) you need to delete from the queue, the above method simply too much of a hassle (well, unless you want to delete *everything*, which would be #postsuper -d ALL). Postfix does not have a function for doing that. Luckily, a search on Google yielded this Perl script that does exactly what I want, removing message(s) from queue based on my keyword. Here is the content of that Perl script called “delete-from-mailq”:

#!/usr/bin/perl

$REGEXP = shift || die “no email-adress given (regexp-style, e.g. bl.*\@yahoo.com)!”;

@data = qx;
for (@data) {
if (/^(\w+)(\*|\!)?\s/) {
$queue_id = $1;
}
if($queue_id) {
if (/$REGEXP/i) {
$Q{$queue_id} = 1;
$queue_id = “”;
}
}
}

open(POSTSUPER,”|postsuper -d -”) || die “couldn’t open postsuper” ;

foreach (keys %Q) {
print POSTSUPER “$_\n”;
};
close(POSTSUPER);

Save the above script to a file say “delete-queue” in your home directory, and make it excutable:

# chmod 755 delete-queue

Usage

Delete all queued messages from or to the domain “iamspammer.com”

./delete-queue iamspammer.com
Delete all queued messages to specific address “bogususer@mydomain.com”

./delete-queue bogususer@mydomain.com
Delete all queued messages that begin with the word “bush” in the e-mail address:

./delete-queue bush*\@whateverdomain.com
Delete all queued messages that contain the word “biz” in the e-mail address:

./delete-queue biz

That's it.

No comments:

Post a Comment