Setting up a web application to send plain text email is easy. What if you need the email to handle other content, such as images or special document formats? This article explains how to design a PHP class for sending email with attachments.
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; }