For 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:
-
The following function is useful if you wish to clear out all files and folders currently sitting in one particular directory. The function itself requires ...
-
Just a simple code snippet to remind myself just how easy it is to spit out content into a text file using PHP. $myFile = "testFile.txt"; $fh = fopen($myF ...
-
SMS Server Tools 3 is a great little SMS Gateway software which you can pair up nicely with some PHP scripts in order to send and receive SMSes. Today's li ...
-
Sometimes Windows can be really, really stingy. For whatever reason, some or other application on Windows may make reference to a particular file on your sy ...
-
Nano is an extremely handy and lightweight text editor that comes with most Linux distributions these days. Today's tip will teach us how to copy and paste ...