PHP Sending attachments with email

We can send attachments with email using mail() function. You will have to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

You have to set multipart/alternative MIME type to send both plain-text and HTML version of the email.

You have to set Content-Disposition: attachment with file name for message to send attachment with email.

You should have to set Content-Type: application/octet-stream with file name for message to send attachment with email.

PHP Syntax :

mail($to,$subject,$message,$headers);

PHP Example : 

<?php

$file = $path.$filename;
$content = file_get_contents( $file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

// header
$header = "From: ".$from_name." <".$from_mail.">\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";

// message with attachment
$message = "--".$uid."\r\n";
$message .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= $message."\r\n\r\n";
$message .= "--".$uid."\r\n";
$message .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$message .= $content."\r\n\r\n";
$message .= "--".$uid."--";

if (mail($mailto, $subject, $message, $header)) {
     echo "HTML Message with attachments is sent successfully..";
} else {
   echo "HTML Message with attachments is not sent successfully..";
}
?>

Output:

HTML Message with attachments is sent successfully..

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

20634