Checking your postfix maillog for bounces and process with ruby
Wednesday 01/30/2008 – Category: Uncategorized
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
2 Responses to “Checking your postfix maillog for bounces and process with ruby”
Leave a Reply
Recent Posts
- Marble Paint
(Friday 02/4/2011 – 1 Comment) - More Flickr Original Updates
(Sunday 01/23/2011 – 13 Comments) - Flickr Original updates
(Saturday 08/7/2010 – 19 Comments) - LED Light for iPhone 4
(Monday 06/28/2010 – 65 Comments)

April 3rd, 2010 at 10:49 am
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.
November 19th, 2011 at 3:03 pm
There are better ways to deal with this. The easiest way is to use an address like ‘bounces@example.com’ as the envelope sender and then pipe all email to this address through a script that processes the emails. If you use VERPs it’s even easier to process the bounces, extracting the correct address from bounces can be a challenge.
Check this out for more information: http://en.wikipedia.org/wiki/Variable_envelope_return_path or http://serverfault.com/questions/48326/how-to-collect-bounces-in-postfix