Postfix Flush the Mail Queue

Traditionally you use the “sendmail -q” command to flush mail queue under Sendmail MTA. Under Postfix MTA, just enter the following command to flush the mail queue:
# postfix flush
OR
# postfix -f

ADVERTISEMENTS

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

postfix-delete.pl script

Following script deletes all mail from the mailq which matches the regular expression specified as the first argument (Credit: ??? – I found it on old good newsgroup)

#!/usr/bin/perl
 
$REGEXP = shift || die "no email-adress given (regexp-style, e.g. bl.*\@yahoo.com)!";
 
@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";
};
close(POSTSUPER);

For example, delete all queued messages from or to the domain called fackspamdomain.com, enter:
./postfix-delete.pl fackspamdomain.com
Delete all queued messages that contain the word “xyz” in the e-mail address:
./postfix-delete.pl xyz

Updated for accuracy.

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source & DevOps topics via:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
62 comments… add one
  • Matt Dec 10, 2007 @ 23:49

    The command for “To remove all bounced mail from Queue, enter:” is incorrect. That command will completely delete all the contents of your Mail Queue.

    When I read this I thought it would eliminate only the bounced back emails that were sitting in my queue. I was wrong. It deleted all 6,000 of the emails sitting in my queue.

    If this post is any sign of the type of information provided on this website, the readers are in for a big surprise…and some pink slips from their employer..

    • Harvey Mar 19, 2011 @ 5:00

      Wow – you seriously just run any commands you find in a forum on your job’s production servers? You deserved that pink slip.

      • MutluMaymun Mar 23, 2011 @ 2:23

        Wow – do you seriously have to write a comment to insult someone after 3 years? While what you said has been said a few lines below, years ago?

        • Callum Feb 28, 2014 @ 14:58

          I agree adding a comment to something a few years ago is just plain stoopid!

          • Eric Aug 7, 2014 @ 20:23

            I agree. Even commenting a few months later is not so bright.

            • Preben Mar 28, 2015 @ 20:29

              Agree, commenting months later is OP.

              • AgreeingGuy Sep 2, 2015 @ 14:09

                And I just felt like agreeing so we can keep on agreeing for the coming years ^_^

                • ErenPhayte Oct 14, 2015 @ 13:49

                  Agreed!

                  • kmaq Oct 22, 2015 @ 23:51

                    Yeah, agreed!

                    • Justin Foley Nov 4, 2015 @ 14:58

                      Keep this thread alive!

                    • SuferDude Feb 26, 2016 @ 17:33

                      Totally, keep things up to date and real man!

                    • Retraut Mar 10, 2016 @ 17:43

                      I agreed with you!

                    • Virax May 16, 2016 @ 16:27

                      Im fucking agree too xD

                    • Mani May 30, 2016 @ 5:16

                      Still Agreed!

                    • So agree ! Oct 6, 2016 @ 8:56

                      I too am agreeing so much on this !

                    • Myself Nov 8, 2016 @ 4:16

                      Is this thing still going?

                    • Artem Dec 31, 2016 @ 0:09

                      Have to agree at the end of 2016

                    • Jon Doe Mar 28, 2017 @ 12:32

                      March 2017, stop being ridiculous guys!

                    • Nigel Danvers Apr 3, 2017 @ 17:03

                      April 2017 standing by.

                    • Chris May 6, 2017 @ 5:18

                      May 2017 standing by!

                • Arunava Sep 6, 2016 @ 10:50

                  LoLoLoL
                  okay, but, seriously folks, i cant find a /deferred directory even.
                  I want a shell command to delete mails queued to a particular person, not everything.

                  • Trumpf Jan 24, 2017 @ 9:59

                    Totally agree !

    • Segun Adebayo Jun 1, 2016 @ 14:05

      almost 9 years after, …. I agree!

      • Richard Iddings Oct 31, 2016 @ 22:13

        I disagree for no other reason than to change it up after 9 years.

        • Kunal Sali May 21, 2017 @ 20:28

          LOL, I agree as well . You know what I mean.

  • 🐧 nixCraft Dec 11, 2007 @ 8:45

    Matt,

    thanks for the heads up. It was a typo. The post has been updated

    • TheSuspect Mar 27, 2017 @ 12:04

      I agree

  • Henk Dec 11, 2007 @ 15:46

    I think matt deserves a pink slip from his employer, because he uses commands found on random sites without even checking what the effects are!

    • The D Dec 11, 2017 @ 6:34

      Happy Birthday Comment! The big one, zero!

  • Jim Apr 24, 2008 @ 18:30

    I’ve found this code on two different blogs and have received compilation errors both times similar to:

    Unmatched right curly bracket at ./delete-queue line 9, at end of line
    (Might be a runaway multi-line ;; string starting on line 5)
    syntax error at ./postfix-delete.pl line 9, near “}”
    Execution of ./postfix-delete.pl aborted due to compilation errors.

    I’m more of a PHP person so Perl’s not my thing. I know syntax is really important and I’ve double and triple checked to make sure things are correct, including composing in vi, pico and bbedit editors.
    ??

  • Manuel May 2, 2008 @ 1:20

    Wow This is a seriously crappy coding job. Who writes this stuff? I cleaned this up to not only make sure this was scoped correctly, but also try to have a novice perl user understand it.

    #!/usr/bin/perl

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

    my %Q;
    my $queue_id;
    my @data = `/usr/sbin/postqueue -p`;
    foreach my $line (@data) {
    if ($line =~ /^(w+)(*|!)?s/) {
    $queue_id = $1;
    }
    if($queue_id) {
    if ($line =~ /$REGEXP/i) {
    $Q{$queue_id} = 1;
    $queue_id = “”;
    }
    }
    }

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

    foreach my $key (keys %Q) {
    print POSTSUPER “$keyn”;
    }
    close(POSTSUPER);

    Hopefully this helps.. I cannot confirm that this works, just cleaned it up so that it makes sense.

  • pd Jul 25, 2008 @ 2:08

    is there someone help me out? i need scripts to check how many emails bounced or deferred or sent?
    if bounced or deferred then why? like full details message?

  • Sean Nov 7, 2008 @ 15:27

    Manuel, learn to indent.

  • somono Feb 11, 2009 @ 8:08

    If a queue_id of – is specified, the program reads queue IDs from standard input. For example, to delete all mail with exactly one sender info@msn.com :

    mailq | tail +2 | grep -v '^ *(' | awk  'BEGIN { RS = "" }
                  # $7=sender, $8=recipient1, $9=recipient2
                   { if ($7 == "info@msn.com")
                   print $1 }
                  ' | tr -d '*!' | postsuper -d -
  • salman Jun 25, 2009 @ 9:43

    thanx alot alot ………………. for the script it works very very very well …… very very very well done …. !!!!!!!!!!!!!!

  • lemsx1 Mar 4, 2010 @ 18:09

    Some say Perl is becoming a lost art 😉 Here is my Ruby re-write (a bit more efficient. it uses practically no memory)

    Save as postfix-purge-queue and run every 1 min from a cron job.

    Change the path to match your own binaries. This assumes Solaris (+ blastwave) paths:

    #!/opt/csw/bin/ruby
    # vi: ft=ruby :
    #
    #  !! lemsx1 $$@$$ gmail !! com
    # 2010-03-04 12:20 EST
    #
    # Cleans postfix mail queue on Solaris
    
    # set debug to true when testing regex:
    debug = false
    
    regex = "example.(com|net|org)|Hosts+ors+domains+names+nots+found"
    
    IO.popen("/opt/csw/sbin/postqueue -p") do |readme|
        q_id = nil
        readme.each do |line|
            if line =~ /^(w+)(*|!)?s/
                q_id = $1
            end
            if q_id
                if line =~ /#{regex}/
                    if debug
                        puts "matching #{q_id}"
                    else
                        `/opt/csw/sbin/postsuper -d #{q_id} > /dev/null 2>&1`
                    end
                q_id=nil
                end
            end
        end
    end
  • Alessandro Apr 5, 2010 @ 12:02

    It’s works for me. Very nice Script VIVEK.

  • nxvir Feb 9, 2011 @ 11:12

    How to read mail in queue? I could not find that command. Like we do in
    exim -Mvh id
    exim -Mvb id

    What is the command for postfix?

    • Patrick Matsumura May 27, 2011 @ 10:21

      Just use mailq

  • Kwex Jun 12, 2011 @ 20:20

    I use Fedora and had problems running this script. I replaced with this line

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

    and it worked fine.

    Thanks!

    • cormos Nov 3, 2014 @ 0:51

      Thank you Kwex, is working in a cron job on Debian thanks to your message.

  • Roman Jun 16, 2011 @ 8:45

    Cool, thanks for the script, worked just fine at my end, just change the paths in the script and that’s it.

    Thanks again!

  • Luigi Molinaro Nov 8, 2011 @ 11:30

    Thanks fot your awesome works !

  • Ali Ramzan Dec 21, 2011 @ 5:59

    My requirement is postfix send 10emails in 1min.Whole postfix server send just 10 emails in 1min.

    How can i do this ? any one help me?

  • Jose Jan 16, 2012 @ 15:47

    All scripts in this thread are gonna FAIL because the lines provided by “postqueue -p” can generate the following two lines, being the second an explanation of the first:
    0EE281EAE6C 78231 Mon Jan 16 00:35:08 aaa@hotmail.com
    (line including for some reason a mail from yahoo, like recipient@yahoo.com )

    and if you run it against the domain .*@yahoo.com, the script is gonna delete the entry from domain aaa@hotmail.com, when it shouldn’t.

    To solve it, you should have this:

      if (/^(w+)(*|!)?s/) {
         $queue_id = $1;
      } else {
         $queue_id = "";
      }
    
    Instead of just this:
      if (/^(w+)(*|!)?s/) {
         $queue_id = $1;
      } else {
         $queue_id = "";
      }
    

    (The mighty Ruby script will fail for the same reason, and is gonna be fixed as well with the “else” help)

    • Steve Aug 20, 2012 @ 16:04

      Maybe I’m missing something here, but your two code blocks are identical…what are you saying should be changed, Jose?

  • Ashish May 3, 2012 @ 1:35

    Hi Vivek,
    Could you please guide me as to how to use the command to kill all the queue mails in the post fix, Sorry I am new to Linux and Perl, I have no idea what i am dealing with please help me out, Following your instruction above i created the perl file, when i tried the command ./postfix-delete.pl yahoo.com i received the error that
    root@mail:/etc/perl# delete.pl yahoo.com
    -bash: delete.pl: command not found.
    Can anyone please help me out with this, I am receiving 25000 spams everyday.

    • Prashant Nov 10, 2014 @ 10:49

      same here … is it we are putting the script in the wrong folder

  • Orango Tango Jul 20, 2012 @ 13:36

    Thanks mate ! Script worked as a charm !

  • Leo G Apr 18, 2013 @ 12:31

    Thanks a lot vivek, The script is awesome

  • middlewhere Aug 27, 2013 @ 23:40

    saved me hours – thanks

  • Toff Aug 29, 2013 @ 22:41

    mailq |awk ‘{print $1}’ |grep -E “[a-Z 0-9]{13}” |xargs -I {} postsuper -d {}

  • Mac Oct 15, 2013 @ 22:35

    postsuper -d ALL deferred
    Worked like a champ, I had forgotten the command trying to setup a smart host to relay through and had clogged up the mailq on the server.

    : )

  • BetaBoy Jul 11, 2014 @ 9:24

    I think he mean the

    } else {
    $queue_id = “”;
    }

    part is added to prevent grepping the dest. server reject message.

  • Prashant Nov 10, 2014 @ 10:46

    HI,

    In which folder should this postfix-delete.pl script be kept , as the command results in file not found if kept in root

  • christian Nov 20, 2014 @ 15:58

    Awsome thx dude saved my time loads
    x

  • Mijo Jan 14, 2015 @ 10:22

    many many thanx to you……script and command works like charm 🙂

  • Preben Mar 28, 2015 @ 20:28

    +1 commenting months after is OP.

  • snka Aug 28, 2015 @ 23:09

    Thanks Vivek

  • JoeAvrg Jan 5, 2016 @ 22:27

    2016 and I’d still agree to this.

  • Someblackman Onapc Nov 2, 2016 @ 14:41

    Agreed

  • AgreeIn2017 Mar 4, 2017 @ 17:39

    Hi, still-relevant post from 2007! I’m from the FUTURE and I also agree!!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.