Reading Rawmails using PHP

posted in: PHP | 0

Summary:

Reading Raw mail Using PHP.

Install the PEAR library mimeDecode in server
Following Code is Used to read the RAW mail 

require (“mimeDecode.php”);

// Receive the entire email to a string

$stdin = fopen (‘php://stdin’ , ‘r’);

$whole_mail = ”;

while (!feof ($stdin))

{

$line = trim(fgets($stdin, 4096));

$whole_mail .= “\n”.$line;

}

fclose ($stdin);

// Parse the email

$md = new Mail_mimeDecode(trim($whole_mail));

$msg = $md->decode(array(‘include_bodies’ => true, ‘decode_bodies’ => true, ‘decode_headers’ => true));
// Recipient  email

We can get recipient email address using following line:

$target_email = $msg->headers[‘x-original-to’];

// Sender email

We can get sender email id using :

$sender_email = $msg->headers[‘sender’];

// Reading Body of mail

 We can read the body of raw mail using following code, it handles all type of headers (gmail, yahoo, hotmail, live, in, aim, aol and Comcast domains )

if (!empty($msg->parts)) {

foreach($msg->parts as $part) {

if (@$part->disposition == ‘attachment’) {

$hasattachments = true;

} else {

$body = $part->body;

}

}

} else {

$body = $msg->body;

}

// For reading the attachments

 Following code is used to read the attachment and create the attachment file in the server.

foreach($msg->parts as $part) {

if (@$part->disposition != ‘attachment’)

continue;

if (strpos(@$part->headers[‘content-disposition’],’filename=’)) {

$filename = substr(stristr($part->headers[‘content-disposition’],’filename=’),9);

}

else if (strpos(@$part->headers[‘content-type’],’name=’)) {

$filename = substr(stristr($part->headers[‘content-type’],’name=’),5);

}

else if (!empty($part->headers[‘filename’]))

$filename = @$part->headers[‘filename’];

else if (!empty($part->headers[‘name’]))

$filename = @$part->headers[‘name’];

else

$filename = “Attachment” . $i++ . “.bin”;

$filename = trim($filename, ‘\'”‘);

$ size = strlen($part->body);

file_put_contents(SERVER PATH . $filename, $part->body);

Chmod (SERVER PATH. $filename, 0666);

}

Previous Post
Next Post

Leave a Reply