A MIME Mailer Class - Adding an Attachment (
Page 3 of 4 )
function add_attachment($file_path)
{
if($file_path != "")
{
$this->files[] = $this->set_file_section($file_path);
}
}
function set_file_section($file_path)
{
if($str = file_get_contents($file_path))
{
$str = file_get_contents($file_path);
$bname = basename($file_path);
$str = chunk_split(base64_encode($str));
$section .= "--MIME_BOUNDRY\n";
$section .= "Content-Type: ".$this->determine_mime($file_path)."; name=\"$bname\"\n";
$section .= "Content-disposition: attachment\n";
$section .= "Content-Transfer-Encoding: base64";
$section .= "\n\n";
$section .= "$str";
$section .= "\n\n";
return $section;
}
else
{
$problem = "";
if(!file_exists($file_path))
{
$problem = "File could not be found";
}
echo("<strong>unable to load specified file $file_path in set_file_section method</strong> <br>$problem");
exit();
}
}
The "add_attachment()" method is pretty simple. It accepts the string path to a file to attach as an argument. It calls the "set_file_section()" method which loads the file, encodes it and places it in the proper mime content. In order to insert the proper mime type for the file into the string, we need to send the file name to a function that determines the mime type based on the file extension. There are a lot of these functions available on various sites and more complex classes that use the mime types file that is used by Apache.
For this class I have written a basic mime type function that supports the formats I most commonly encounter in my work. If you have additional ones that you wish to support, adding mime types to this function is as simple as adding to the switch construct.
function determine_mime($name)
{
$str = basename($name);
$name_arr = explode(".",$str);
$len = count($name_arr) - 1;
$name_arr[$len] = strtolower($name_arr[$len]);
switch($name_arr[$len])
{
case "jpg":
$type = "image/jpeg";
break;
case "jpeg":
$type = "image/jpeg";
break;
case "gif":
$type = "image/gif";
break;
case "txt":
$type = "text/plain";
break;
case "pdf":
$type = "application/pdf";
break;
case "csv";
$type = "text/csv";
break;
case "html":
$type = "text/html";
break;
case "htm":
$type = "text/html";
break;
case "xml":
$type = "text/xml";
break;
}
return $type;
}