Wednesday, December 23, 2009

Send Mail With Attachment in php

 If u want to send a email using php mail function with attachment a zip or any file following code will help u to send it.

$fileatt = ""; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$fileatt_name = ""; // Filename that will be used for the file as the attachment



$to = 'youraddress@example.com';                          //define the receiver of the email 

$subject = 'Test email with attachment';                   //define the subject of the email 

$random_hash = md5(date('r', time()));                 //create a boundary string. It must be unique use md5 function for it.


$random_hash = md5(date('r', time()));                 //create a boundary string. It must be unique use md5 function for it.
$mime_boundary = "==Multipart_Boundary_x{$random_hash}x";
$headers = "From: support@campus100.com\r\nReply-To: support@campus100.com";   //define the headers we want passed. Note that they are separated with \r\n

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";   //add boundary string and mime type specification
//$headers .= "Content-type: text/html\r\n";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks

$file = fopen($destination,'rb');
$data = fread($file,filesize($destination));
fclose($file);
$data = chunk_split(base64_encode($data));
//define the body of the message.

//ob_start();         //Turn on output buffering
$fileatt_type=$_FILES['attachFile']['type'];

$textTosend='.nl2br($body).';

$textTosend .= "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" .
$textTosend . "\n\n";



$textTosend .= "--{$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";
unset($data);
unset($file);
unset($destination);
unset($fileatt_type);
unset($fileatt_name);

if(mail( $to, $subject, $message, $headers ) ){

echo "Mail sent" ;

}else{
   echo "Mail send Fail";
}

?>




No comments:

Post a Comment