Email forward to PHP script always bounces
I am trying to execute a PHP script when an email is received on a managed server, and I only have access through cPanel.
Following this instructions I was able to get the script to work, but it still bounces the content of the email back to the sender.
I tried to read the stdin as suggested by this post, but nothing changed. Adding a $emailtext = mailRead(); does read the stdin, and adding echo $emailtext; it writes the email text in the bounced email (so I get the text twice, one from my echo and once at the end of the bounced email.)
The bounce is sent by Mail Delivery System <Mailer-Daemon@sti.stidev.com>, here is the content (in bold italic the parts that I changed):
This message was created automatically by mail delivery software.
A message that you sent could not be delivered to one or more of its recipients. This is a permanent error. The following address(es) failed:
pipe to |/path/to/php/script generated by firstname.lastname@example.org
The following text was generated during the delivery attempt:
------ pipe to |/path/to/php/script generated by email@example.com ------
X-Powered-By: PHP/5.2.17 Content-type: text/html
here is see any output echo-ed by the script
------ This is a copy of the message, including all the headers. ------
How do I get rid of that bounce email?
Add a -q at the end of the shebang.
Here are the steps that finally gave me a working script:
- In cPanel create an email forwarder to a script file
- Make sure that the script file does not contain /n/l, but only /n (no Windows new lines in Linux)
- Make sure that the script starts with the correct shebang: #!/usr/bin/php -q
- Set the script permission to executable
Removing the -q at the end of the shebang causes the email to bounce back to the sender. Any text echo-ed by the php script is included, and it can be useful for debugging.
Points 2 and 3 made me waste hours. I spent time also trying to read the stdin and trying different exit values: the stdin doesn't need to be read as explained here, the script doesn't need to exit(0) or any exit at all.
Of course this worked for me, and may not work with different configurations. But here is my answer, hoping that it will help someone else.