Setup Postfix to forward incoming email to PHP

>Setting this up took me a couple of minutes — finding the reason why it didn’t work a couple of hours. The question has hundreds of hits on Google, a simple answer hasn’t. Hope this helps someone somewhere you.

Create script to parse incoming mail

<?php
  $data = file_get_contents("php://stdin");
?>

Add a new email address to Postfix configuration

sudo vi /etc/aliases

and add the following line (everything on one line)

email+to+redirect: "| php -q /home/user/full/path/to/your/new/script.php"

Apply the changes to the aliases by running

newaliases

To make sure Postfix will pick up the newly added alias soon. If you’re in a hurry, do a

/etc/init.d/postfix reload

Aaaaaah!

One thing that took some time to figure out: my php script ran ok from the prompt, I had supplied it with test data and I saw all the expected data in my database. Yet, when I triggered the script by sending an email to the new address, Postfix bounced it right back at me, saying

The e-mail system was unable to deliver the message, but did not report a specific reason. Check the address and try again. If it still fails, contact your system administrator.
 
< xxx.yyy #5.0.0 X-Postfix; Command died with status 255: " php -q /home/user/full/path/to/your/new/script.php"&gt;

In the end, the reason for this error is simple. It is Postfix telling me PHP stopped executing the script as it found an error. In my case, the error occured when the script ran as user Nobody. When tested from the prompt, I didn’t get the error, as the user had sufficient rights.

This entry was posted in coding. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Mr.n
    Posted April 10, 2009 at 2:59 pm | Permalink

    Thanks for these info, so helpful…
    Can you publish a php script or a guide on how to read the subject, from, to, body… fields in php and use them inside the script??

  2. Va75a77a
    Posted September 18, 2009 at 8:43 pm | Permalink

    Hi,

    I have setup an alias in postfix and it tries to write a file, but it does get a permission denied error, is there a way around this? Thank you for the code above.

  3. hisam
    Posted March 11, 2010 at 8:11 pm | Permalink

    what shud i give instead of email+to+redirect: is it his@abc.co or just his. i get error wen i give his@abc.com and do newaliases. pls help!

  4. Posted March 16, 2010 at 2:50 pm | Permalink

    Hi hisam, should be only the part before the @, so in your case just his

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

  • recent beluisterd