Sending (or piping) emails to a php script would allows a whole world of fun. I had a spare 30 minutes the other night so I sat down, read a few blog posts and forums and set up emails to pipe to a php script.
The first step for me was to set up a new subdomain in cPanel. This allows me to only send (or pipe) specific email to the script and means I can run a catch-all wildcard forwarder on all emails to that subdomain.
In cPanel I created the subdomain in the normal way. Then I navigated to ‘Email Management Tools -> Default E-mail account’, chose the new subdomain from the dropdown list, clicked ‘Advanced Options’ and selected the radio button for ‘Pipe to a Program’.
In the textbox I added the name of the file that would be used to process the emails. In my case catcher.php which I had already created in the root of my site (not in public_html).
Cpanel is clever enough to add your sites root folder to the name you specify, so will be altered to something like ‘/home/youraccount/catcher.php’
The next step was to prepare catcher.php to deal with the emails being piped to it. Open the file and change the contents to something along the lines of:
The first line of the script is very important and will tell the email pipe to use php. If your php install is not found at the location show, change it so it is. The -q part tells the pipe not to bounce an email back to the sender. A good thing as we can do that manually in the script.
Make sure you change the permissions of the script to be executable by the email pipe. chmod 755 should do fine.
The script itself will grab the emails contents using fopen on php://stdin which is where the email is temporarily stored. You can then manipulate it using such functions as preg_match to grab the parts you want.
The beauty of this method is it will catch all email to that subdomain, so you can create addresses which include the users id and a hash which can be temporary:
which you can use to ensure you only act on emails from the intended user.
Note: If you are using -q but still getting bounces, be sure the script is not outputting any data. That means once you have tested it, no print, no echo, no var_dump. When you run the script directly you should see a blank screen and the source code should be empty.