How To Easily Parse Incoming Emails From Postfix

Step 1: Postfix Config

I’m going to assume you have postfix and your domain dns already setup.  Adding an incoming email that you can parse with your favorite programing language is fairly easy from this point.

Open up “/etc/postfix/”. You’re going to need to enable virtual alias support, if you don’t have it already.  This could cause issues if you’re using mydestination, the postfix default, instead of virtual_alias_domains.  You might want to look into moving to virtual alias for postfix as it’s generally considered more flexible.  If you are already using virtual_alias_domains/virtual_alias_maps then its safe for you to continue.

Step 2: Virtual

You probably have a setup in your “/etc/postfix/” similar to this. Find and open the file that’s your virtual_alias_maps file.  Mine is shown below as “/etc/postfix/virtual”

virtual_alias_domains =
virtual_alias_maps = hash:/etc/postfix/virtual

The contents of my virtual file looks similar to this.  This example would post email from [email protected] to the the alias: postEmailAlias

[email protected]        postEmailAlias

Another example, virtual alias’s are processed top down, so [email protected] will forward to sales user, then every other email (* will forward to postEmailAlias.

[email protected]	sales
*	postEmailAlias

Step 3: Setup Alias

This file is located at “/etc/alias”. In this file you’ll be able to point a fake system user, an alias, to a system command and postfix will deliver to it. Here are a couple examples of what you can do.  We’ll be using the same user we just made up in the postfix virtual config “postEmailAlias”

If you want to take in an email and post the entire contents over http to a url then you’ll want the alias like this.

postEmailAlias: "|curl --data-binary @-"

If you want to take in an email and pass the entire contents to a script, like php, you can do that like this. If this script needs file access, you can run into problems with permissions because postfix level of permissions. So the curl method above might be better.

postEmailAlias:      |"php /var/www/website/scripts/emailPost.php"

Step 4: Reload Postfix

Redo virtual lookup table index.

postmap /etc/postfix/virtual

Redo alias lookup table index.

postalias /etc/alias

Restart or reload postfix to take affect.

service postfix restart

Step 5: Send Test Email

Send an email to [email protected] and you should be able to see it hit postfix/php via tail command. Looks for any errors or permissions issues. If your php script returns any the email might bounce.

tail -f /var/log/mail.log

Leave a Reply

Your email address will not be published. Required fields are marked *