sendmail queue - display number of messages per domain

Well, if you are going to use perl, might as well go all the way.

The following is a fairly imperfect way of counting the number of messages per domain:

#!/usr/bin/perl

use strict;

my @mailq = `cat /home/users/rilindo/mailq`; #Had to simulate the output of the mail command here. Change this to the actual mailq path, e.g. /usr/bin/mailq
my %domains = ();

foreach my $m (@mailq) {
    $m =~ s/^\s+//;
    $m =~ s/\s+$//;
    $m =~ s/>//;
    next if $m =~ /Queue/;
    if ($m =~ /\d\d:\d\d:\d\d/) {
        $domains{(split(/@/,$m))[1]}++;
    }
    else {
        $domains{(split(/@/,$m))[1]}++;
    }
}

foreach my $d (keys %domains) {
    print $d . " has $domains{$d} message(s)" . "\n";
}

Essentially, we send an output of the mailq command into an array and iterate. For each record in the array, we strip the leading and trailing spaces/newlines, and then split at the "@" sign. Then we insert domain as a key (if it doesn't exist) and then increment it in a hash. On the next try, it will simply increment the value if the same domain was found. From there, we loop through the hash and then print out the domain with the total number of matches.

The result:

[rilindo@localhost ~]$ ./parsemail.pl 
domain.com has 6 message(s)
domain3.com has 2 message(s)
domain1.com has 2 message(s)

Like I said, its not perfect, but it does the job. If nothing else, it will give you an idea of where to go from here.

Incidentally, since it appears you know perl, review of Perl's hash data structures will prove to be very useful:

http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/hash/

Or:

http://perldoc.perl.org/perldsc.html


Try this:

# mailq -v | awk 'BEGIN { FS = "@" } \
!/^[a-zA-Z0-9-]|^[ \t]+(\(|\/|Total requests:)/ { print $2 }' | sort | uniq -c