Thursday, March 22, 2012

Parsing E-mail with PHP

I recently had a need to parse e-mail being piped in from Postfix and insert the exploded headers and message into a database running MS SQL.

It sounds simple enough, and once I started doing some searching, it seems that a ton of people have all sorts of ways of doing this - mostly with PHP.

I tried using Python first, but ended up deciding that PHP was just a better (and simpler) solution for this. Until this week, I had no idea that PHP could be so powerful for SysAdmin type scripting. In fact, before this week, I knew very little about PHP period.

Once I started looking, I found many examples. The thing is, no single example I found worked for me (at least entirely) so I thought I'd share the script that finally did work, in hopes it could help someone else out with a similar problem.

This script assumes you have PHP with the MS SQL extensions as well as FreeTDS installed.

Here is the script:



The script accepts e-mail via STDIN, so to test the script itself you can create a 'sample' e-mail file such as this:





Then you can place your sample emailfile in the same directory as your PHP script and then use cat to pipe the e-mail file to PHP like this: cat emailfile | postfix.php After that configure Postfix to forward all mail to your PHP script, and you are all set. I'll cover the Postfix configuration in a seperate post.

2 comments:

  1. Hi Jayson,

    I am currently working on the same, I am using your script. it works file with the test message.

    But when I pipe in the master.cf of postfix config, it is not working.

    Nevertheless it gave me some very good idea on PHP and SQL scripting.

    Thanks

    ReplyDelete
  2. This is similar to how we are doing it: http://jeroensmeets.net/setup-postfix-to-forward-incoming-email-to-php/

    ReplyDelete