PDA

View Full Version : Processing incoming mail with PHP


Valen
08-06-2004, 03:30 PM
This may not be something that's done very often (unless you're writing an online mail system I guess) but I'm trying to figure out how to pipe an incoming email to a PHP script. I'm hosting with pair.com (they run freeBSD), and their control panel allows you to do this. The problem is, it doesn't work for me. :)

What I tried to do is pipe mail to a script which then uses php://stdin to try to grab the email. I found one article (seems to be plastered all over the web) that shows how to do this -- http://gvtulder.f2o.org/articles/incoming-mail/ From my observation, it seems that the script is never executed (either that or it can't grab the email). It's very strange because if I send an email, it doesn't bounce. But once I delete the script file from the server it instantly bounces.

Any *nix experts here who can help? :)

Here's the code (pretty much like in the article except I try to dump it to a file)

<?php

$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);

$outfile = fopen("test.txt", "w");
fwrite($outfile, $email);
fclose($outfile);

?>

oNyx
08-06-2004, 04:35 PM
Eventually you fail to write the file. Add some error checking for excluding that as a reason.

See here:
http://www.php.net/manual/en/function.fwrite.php

Sillysoft
08-06-2004, 05:01 PM
I have never used PHP to read from stdin, however in other languages you can read from stdin forever without getting an EOF (unless the user types control-d or something). So my guess is that you are forever blocking in the 'while (!feof($fd))' loop. It is just a guess, you could test it by writing to a file within the loop (or something).

Valen
08-06-2004, 05:09 PM
Neither of those seem to be a problem. I added code to send an email to me before the main code runs, and after. I get the emails when I run the script directly from a browser, but sending email to the script doesn't do anything. Looks like it's not being executed. What I don't get though is why. :confused: I'm not getting bounced emails, so it knows that the script is there but it's not executing. Maybe I'm missing some kind of setting somewhere.

Valen
08-08-2004, 09:24 AM
[edit] After combing some PHP mailing lists, I figured out how to get it to work. In case anyone searches for this, my solution was to give qmail the script path like this:

/var/qmail/bin/preline /usr/local/bin/php /script_path/script.php

Kai Backman
08-09-2004, 10:46 AM
Just to give a second solution. I simply have a script that uses Curl to post the email to a specific PHP page. For testing the page always returns a form where you can enter the email into a textbox and run the script again. As the previous mail is stored in the textbox this gives a faster turnaround (and enables manual processing of emails).