1) Locate your maillog (usually in /var/log)

2) If you cat the file, you’ll get output something like:

    Jan 27 01:19:28 145856-web1 postfix/smtp[8994]: DAA77A74568: to=, relay=none,
delay=388925, status=deferred (connect to noemail.org[82.98.86.165]: Connection refused)

3) we want to check for “status=deferred” or “status=bounced”. we’ll do this with the grep command:

    grep “status=bounced” /var/log/maillog | grep -o -P “to=<(.+?)>” > bounces.log

(you may have to sudo if you’re not logged in as root)

The first half grabs the lines from the log that match the status string.

We just want the email addresses, so we use the pipe operator to pass it on for trimming. Using the -o flag you can get exactly what you want from the matching regex (-P flag). In this case, we see the emails are always surrounded by to=<>”.

Your output (saved to bounces.log) should look something like:

 
to=<adf@asdfa.com>
to=<af@asdf.com>
to=<dfda@fad.COM>
to=<adsfa@df.net>
to=<fd@adf.com>
 

I wanted to get the emails nice and trimmed in an array for use in a Rails app:

 
bounce_array = []
unique_array = []
 
File.open(“PATH/TO/LOGS/bounces.log”, “r”) do |maillog|
  i = 0
  maillog.each_line do |line|
 
     puts “Got email #{i} #{$1}”  if line =~ /to=<(.+?)>/i
     i = i + 1
     bounce_array « $1.to_s
  end   
 
  unique_array = bounce_array.select{|e| bounce_array.index(e) !=
    bounce_array.rindex(e)}.uniq
end
 
unique_array.each do |e|
 puts e
end
 

One Response to “Checking your postfix maillog for bounces and process with ruby”

  1. Brian Armstrong Says:

    Nice! Thanks for posted this. Surprised there isn’t a better way to get bounces from postfix other than scraping the logs, but this helps.

Leave a Reply