Need help using php to dissect and store email components

Hi there everyone!

I’m trying my best to Google my way through this issue, but have run into an issue I can’t out-Google. I’m trying to write a script that is receiving an email, breaking it apart into it’s various components and then storing into a database. I would like to store:

from name
from email
to name
to email

Here’s what I’ve cobbled together from various tutorials and demo’s:

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

//split the string into array of strings, each of the string represents a single line, received
$lines = explode("\
", $email_content);
// initialize variable which will assigned later on
$from = "";
$subject = "";
$headers = "";
$message = "";
$is_header= true;
//loop through each line
for ($i=0; $i < count($lines); $i++) {
	if ($is_header) {
		// hear information. instead of main message body, all other information are here.
		$headers .= $lines[$i]."\
		// Split out the To portion
		if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
			$to = $matches[1];
		$toregexp = '/To:\\s*(([^\\<]*?) <)?<?(.+?)>?\\s*\
		if(preg_match($toregexp, $email_content, $to_dissection)) {
			$toname = $to_dissection[2];
			$toemail = $to_dissection[3];
		// Split out the subject portion
		if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
			$subject = $matches[1];
		//Split out the sender information portion
		if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
			$from = $matches[1];
		$fromregexp = '/From:\\s*(([^\\<]*?) <)?<?(.+?)>?\\s*\
		if(preg_match($fromregexp, $email_content, $from_dissection)) {
			$fromname = $from_dissection[2];
			$fromemail = $from_dissection[3];
	} else {
		// content/main message body information
		$message .= $lines[$i]."\
	if (trim($lines[$i])=="") {
		// empty line, header section has ended
		$is_header = false;

My issues are many. I’ve got from and to names that don’t reflect the true data,
the from address will be the original sender and not the most recent sender if
it’s forwa

forwarded and finally, the body is showing up empty. Clearly, I’m not handling this properly. With all the trouble-ticket like systems out there, there has to be a fairly bulletproof method of handling this, doesn’t there?

Any help would be greatly appreciated!