Friday, December 18, 2015

HOWTO Flush the Mail Queue on Postfix

Flush the Mailq:

To flush mail queue under Postfix, just enter the following command to flush the mail queue:
$ postfix flush

$ postfix -f

To see mail queue, enter:
$ mailq

To remove all mail from the queue, enter:
$ postsuper -d ALL

To remove all mails in the deferred queue, enter:
$ postsuper -d ALL deferred

Delete E-Mails with one Perl Script
The following script deletes all E-mails from the mailq which matches the regular expression specified as the first argument:


$REGEXP = shift || die "no email-adress given (regexp-style, e.g. bl.*\!";

@data = qx</usr/sbin/postqueue -p>;
for (@data) {
  if (/^(\w+)(\*|\!)?\s/) {
     $queue_id = $1;
  if($queue_id) {
    if (/$REGEXP/i) {
      $Q{$queue_id} = 1;
      $queue_id = "";

#open(POSTSUPER,"|cat") || die "couldn't open postsuper" ;
open(POSTSUPER,"|postsuper -d -") || die "couldn't open postsuper" ;

foreach (keys %Q) {
  print POSTSUPER "$_\n";

For example, delete all queued messages from or to the domain called, enter:

Delete all queued messages that contain the word "xyz" in the e-mail address:
./ xyz

Delete E-Mails with one one-liner:
Another way to check and delete E-Mail from the mailq is a simple "one-liner":

Check the E-Mails:
for i in `mailq | egrep "^[0-9A-F]" | grep '' | cut -c1-12 | sed s/\*//g` ; do echo $i; done

Delete the E-Mails:
for i in `mailq | egrep "^[0-9A-F]" | grep '' | cut -c1-12 | sed s/\*//g` ; do postsuper -d $i; done