Grabbing Email Addresses From Postfix Logs

In a recent incident, I was asked to provide a list of destination addresses being delivered to a particular mail server. Here's an example line from a #Postfix log:

Dec 29 05:00:51 mail01.test.example.com postfix/smtp[28704]: AF02145249: to=<emailtest.address@gmail.com>, relay=gmail-smtp-in.l.google.com[209.85.232.27]:25, delay=0.69, delays=0.01/0/0.16/0.52, dsn=2.0.0, status=sent (250 2.0.0 OK 1544545651 n189bb201234abc.123 - gsmtp)

From that log line, you can see that the #email address is surrounded by the angled brackets, “<” and “>”. Those brackets are preceded by the text “ to=”.

From this fantastic stackoverflow page I found some very useful grep commands for use in compiling part of this answer.

I decided to go with the fastest #grep answer, since I was dealing with multiple gigabytes of mail logs from the Postfix Mail Transfer Agent (MTA):

grep -Po ' to=<\K[^>]*'

Now I need to explain what each bit of that means. (Using the GNU Grep 3.3 manual)

When ran against the log line shown at the beginning, you get the following output:

$ cat tmp2.txt | grep -Po ' to=<\K[^>]*'
emailtest.address@gmail.com

If you are interested in using regexes more, the RegExr site is a visual regex learning tool. You can use it to build up regexes slowly while understanding exactly what they do. You can also paste in a pre-existing regex to see if the site can describe what it does for you.