Thursday, June 14, 2012

Sample PHP code for sending email with File Attachment






The mail() function  allows us to directly send email from php script.  This function allows sending header information as parameter.

This feature can be used for attaching files with the email sent from mail() function.



The below function mail_attachment can be used for sending email with file attachment.




function mail_attachment($filename, $path, $mailto, $from_mail, $from_name,  $subject, $message) {
    $file = $path.$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()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$from_mail."\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 in MIME format.\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"; // 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"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
    }
}

This function can be called as below.

$my_file = "file1.pdf";
$my_path = $_SERVER['DOCUMENT_ROOT']."/myfiles/";
$my_name = "raj";
$my_mail = "info@domain.com";
$my_subject = "Email Subject ";
$my_message = "Refer the attached file.";
$to_email="to@domain.com";

mail_attachment($my_file, $my_path, $to_email, $my_mail, $my_name, $my_subject, $my_message);


You can subscribe to our Email posts, and you can bookmark this blog for further reading, or you can subscribe to our blog feed.

No comments:



Thanks for visiting our blog


twitterrss facebook linkedin YouTube subscribe


Subscribe via email

Enter your email address: