Tuesday, January 13, 2009

mail attachment code, php

Hi All,
This is the simple mail attachment function.

function mail_attachment($filenam, $filepath, $mailto, $subject, $message) {
$filename = $filenam;
$file = $filepath;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use diff. tyoes here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
mail($mailto, $subject, "", $header);
}
?>
save the above file as mail_attachment.php.

how to use it.....
include "mail_attachment.php";
$destination="filepath";
/*
e.g
$file = $_FILES['attachement']['name'];
$tepmfile = $_FILES['attachement']['tmp_name'];
//$destination = $_SERVER['DOCUMENT_ROOT']."uploadedFiles/".$file;
$destination = "uploadedFiles/".$file;

*/
move_uploaded_file($tepmfile,$destination);
$to = "rex.php@gmail.com"; // to email id

//$subject ="your subject";
$msg = "Your message";
// call mail attachment function
mail_attachment( $file, $destination, $to,$subject, $msg);
?>
html code below............

No comments: