Send Email with Attachment :

Sending a plain email is extremely easy. mail function provided in php does everthing you need behind the seen. Only problem can occur when you need to attach one or multiple files with email using your script.

Before starting read or copy this script, would you mind to read and understand about MIME (Multiplupose Internet Mail Extensions) please. Click here to learn about MIME.

Now you are ready !

I'm using simple 2 functions here to do all the jobs. Notes and comments will describe what has been done....

** Script: To send email with attachment  **

** Function: do_Attachment
** Input: ARRAY attachment
** Output : String
** Description: Returns headers and data for 
** one attachment. 
** It Expects an aray with elements type, name 
** and contents. 
** Attachments are base64 encoded. 

function do_Attachment($attachment) { /** send content type each attachment requires content-type and content-transfer-encoding headers */ $headers = "content-Type: " . $attachment["type"]; if(isset($attachment["name"])) { $headers . = "; name=\{$attachment["name"]}\""; } $headers .= "\r\n". "Content-Transfer-Encoding: base64\r\n" . "\r\n" . chunk_split(base64_encode($attachment["content"])). "\r\n"; /*** encode attachment with base64, which prevent from corruption of attachment *** return ($headers); } /* ** Function: sendmail_with_Attachment ** Input : String to, String from , String subject, Array attachment ** Output: none ** Description: Sends attachments via email. The attachment array is a 2 diamentional array. ** Each element is an associative array containg elements type, name and content. */ function sendmail_with_Attachment($to, $from, $subject, $attachment) { //add from-address into header $headers="From: $from \r\n"; //specify MIME version 1.0 $headers.="MIME-Version: 1.0\r\n"; //using multiple parts if(count($attachment)>1) { $boundary = uniqueid("EWSEWS"); $headers.="Content-Type:multipart/mixed". "; boundary = $boundary\r\n\r\n". "This is a MIME Encoded message.\r\n\r\n". "--$boundary"; foreach($attachment as $att) { $headers.="\r\n". do_Attachment($att). "--$boundary"; } $headers. = "--\r\n"; } else { $headers.="do_Attachment($attachment[0])"; } //send message mail($to, $subject, "", $headers); } //add the text in the message $attach[] = array("content"=>"Email with attachment", "type=>"text/plain"); //add script to list of attachments $fp = (__FILE__, "r"); $attach[]=array("name"=>bassename(__FILE__), "content"=>fread($fp,filesize(__FILE__)), "type"=>"application/octet-stream"); fclose($fp); //send email mailAttach("mail_to_address","subject_text-here","$attach"); print("Mail Sent <br>");


Contact us about this script