Mmm, since you're talking about a mail function you'd have to parse out mailbox queues, not something I've done a lot of (and a long time ago.) Basically whatever system you use (let's say, sendmail) you'd have to figure out where the mail is stored and build an app to parse out the mailbox. Lots of command line stuff and permissions issues to deal with, as I recall.
If you use cPanel you can select the Forward > Pipe to Program option and send the incoming mail to a PHP executable.
If you don't you will need to adjust you mail software like rockinbil said, but again, you can run them through a PHP executable. I don't know what software you use, but with cPanel it's simple to get it to the program and with Postfix it's a bit more complicated but nothing too super, extra ugly. (Of course how 'ugly' depends on your definition of 'ugly to code' ... lol)