- Home
- Programming
- PHP
- Pipe email to a php script
Pipe email to a php script
- By Tarik Sabbagh
- Published 26/11/2007
- PHP
-
Rating:




Based on an onld article written in 2002 at evolt.org that explains how to pipe an email to a php script.
This should work with any php CGI build
The below script will process the email and break it into several variables you can use in your own operations. They are:
$from
$subject
$headers
$message
- Copy the below code into a php file emailprocess.php upload to your web server.
- Create a PIPE to the script (available in CPANEL etc)
#!/usr/bin/php -q
<?php
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
// handle email
$lines = explode("\n", $email);
// empty vars
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
?>
NOTE: If you find you are getting bounce messages (even though the script worked) you will find this is caused by the script outputting some data. Ensure you are not echoing data etc. remember this script is designed to be call internally by the mail process not via the browser, so requires no output!
I have used the above script in an email to sms utility i have created, which can also be found on this website.
Based on http://www.evolt.org/article/Incoming_Mail_and_PHP/18/27914
You can download the full script below. comments appreciated
Spread The Word
Attachments
1 Response to "Pipe email to a php script" 
|
said this on 16 May 2008 1:44:48 AM EST
Thasnks for this but It does not correctly for multipart/altnerative formats with boundary's. Any ideas?
|
Author/Admin)