PHP Code to Extract Attachments from Mail Files

PHP-logoFor a recent project I needed to parse .mai mail files to locate any Excel or Zip files that may have been sent through as attachments. The following block of code is the result of my work:


/*
Method for extracting attachments out of .mai Mail files
This example is extracting .xls Excel based on application/vnd.ms-excel content type
*/
 
//Opens .mai file for reading
$handle = @fopen($mailfile, "r");
 
//set up control variables and arrays
$print_flag = false;
$encodedfiles = array();
$encodedfilenames = array();
 
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
if (!(strpos($buffer,'Content-Type: application/vnd.ms-excel;') === false)) {
$print_flag = true;
$content_found = true;
$encodedfile = '';
}
if ($print_flag == true) {
if ((trim($buffer) == Chr(13)) || (trim($buffer) == Chr(10)) || (trim($buffer) == '')) {
if ($content_found == true) {
$content_found = false;
}
else {
$print_flag = false;
$encodedfiles[] = $encodedfile;
}
}
}
if ($print_flag == true) {
if ($content_found == false)
{
$encodedfile .= $buffer;
}
else {
if (!(strpos($buffer,'filename=') === false)) {
$tempname = str_replace('filename="', '', trim($buffer));
$encodedfilenames[] = substr($tempname,0,strlen($tempname) - 1);
}
}
}
}
//close open file handle
fclose($handle);
}
//recreate base64 encoded files as valid files
$runner = 0;
foreach($encodedfiles as $encodedfile)
{
$fp = fopen($encodedfilenames[$runner], 'w');
fwrite($fp, base64_decode($encodedfile));
fclose($fp);
$runner = $runner + 1;
}
?>

Obviously by extending the content types being searched on with a simple or statement, you can alter the script to extract just about any type of attachment, making it quite useful indeed.

It’s fast and appears to work pretty nicely, so hopefully it can be of some use to you then! :)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged .mai, attachment, , , mail, . Bookmark the permalink.
    blog comments powered by Disqus