How to send mail that supports multi-type attachment using php’s mail function
To send an email with php mail() function is quite easy, but when it comes to send attachments with mail() function is a little bit complex. To send an email with mixed content requires to set Content-type header to multipart/mixed.
The message part is always specified in the Boundary section. A boundary always starts with two hyphens followed by unique number and also ends with two hyphens. This number is never a part of the mail body. Attached files are always encoded with the base64_encode() and chunked with the chunk_split() function.
Following is a sample code for sending pdf, doc, images files as an attachment with php’s mail() function.
$fileatt_path = $_SERVER['DOCUMENT_ROOT']."/documents/"; // Path to the file $fileatt_type = "application/pdf"; // File Type $attachement = 'example.pdf'; $fileatt = $fileatt_path.$attachement; if(!empty($username) && !empty($email)){// check to send mail only if username and email is provided $fileatt_type = "application/pdf"; // File Type $fileatt_name = $attachement; // Filename that will be used for the file as the attachment $email_from = "prakashak <prakashak@sambhashanam.com/>"; // Who the email is from $email_subject = "Thanks for your interest"; // The Subject of the email $email_subject .= "<img src='http://www.sambhashanam.com/images/logo.png'/>";//To put logo in the mail body $email_message .= "<b>Dear User,</b><br/>"; // Message that the email has in it $email_message .= "Please find attached file.<br/><br/>"; // Message that the email has in it $email_message .= "<b>Best,</b><br/>"; // Message that the email has in it $email_message .= "<b>Sambhashanam.com</b>"; $email_to = $email; // Who the email is to $headers = "From: ".$email_from; $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); $semi_rand = md5(time());//to create a 32 digit hexadecimal number to create unique number $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n"; $data = chunk_split(base64_encode($data)); $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data .= "\n\n" . "--{$mime_boundary}--\n"; $sent = mail($email_to, $email_subject, $email_message, $headers); |