Monday 18 June 2012

Mail Function with Attachments in php

Mail Function with Attachments in php
<?php
function mailWithAttachments($fileName, $filepath, $mailto, $fromMail, $fromName, $replyTo, $subject, $message) {
    $file = $filepath.$fileName;
    $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()));//for unique number generate
    $name = basename($file);
    $header = "From: ".$from_name." <".$fromMail.">\r\n";
    $header .= "Reply-To: ".$replyTo."\r\n";
    $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.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; 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"; // you can also use different content types 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."--";
    if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // 
    } else {
        echo "mail send ... ERROR!";
    }
}
?>

How can use this function.

$my_file = "demo.zip";
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";
$my_name = "jafar khan";
$my_mail = "jafarkhanphp@gmail.com";
$my_replyto = "jafarkhanphp@gmail.com";
$my_subject = "Mail with attachment.";
$my_message = "Hallo this is testing";
mail_attachment($my_file, $my_path, "jafar_14jan@yahoo.com", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);