Extracting recipient addresses from the Postfix maillog for a given authenticated SMTP sender

May 18, 2015 under Main

This is something I’ve had to do frequently enough, and end up having to reinvent the wheel each time as I never remember exactly how I did it last time.

The problem: given a particular authenticated SMTP username, extract a list of all recipients to which mail was sent from the current maillog file. You may want to first extract the section of the log(s) that you need to cover a specific time period.

Solution:

grep sasl_username=sender@domain.tld maillog | cut -d " " -f 6 | perl -pe 's/://g' | xargs -I MSGID grep MSGID /var/log/maillog | grep to=\< | perl -pe 's/^.+to=\<(.+)\>,.+$/$1/g'

Replace sender@domain.tld with the username your sender authenticated as.

The tricky part is that the line Postfix logs when authenticating an SMTP connection only contains the message ID, not the recipient address(es). So we have to extract those message IDs and then re-parse the maillog to search for the line which contains the message ID and the string “to=”. Then extract the address from the¬†matching log entry.

You can pipe through uniq and sort if you want a sorted list of unique addresses, or leave as-is if you just want the list in the order logged by Postfix.

comments: Comments Off on Extracting recipient addresses from the Postfix maillog for a given authenticated SMTP sender