views:

139

answers:

3
+2  Q: 

php email piping

Im trying to setup a program that will accept an incoming email and then break down the "sender" and "message" into php variables that i can then manipulate as needed, but im unsure where to start.

I already have the email address piped to the php file in question (via cpanel)

+1  A: 

Start with:

$lines = explode("\n",$message_data);
$headers = array();
$body = '';

$in_body = false;

foreach($lines as $line)
{
     if($in_body)
     {
          $body .= $line;
     }
     elseif($line == '')
     {
          $in_body = true;
     }
     else
     {
          list($header_name,$header_value) = explode(':',$line,2);
          $headers[$header_name] = $header_body;
     }
}

// now $headers is an array of all headers and you could get the from address via $headers['From']
// $body contains just the body

I just wrote that off the top of my head; haven't tested for syntax or errors. Just a starting point.

Josh
+2  A: 

Have a look at the eZ Components ezcMailParser class. You'll need to implement an interface - ezcMailParserSet - to use it.

rojoca
I like this solution better than my own
Josh
+1  A: 

Here is working solution

#!/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;
}
}
echo $from;
echo $subject;
echo $headers;
echo $message;
?>

Works like a charm.

Patrick