PHP Send Email with HTML and Multiple Attachments

Tech Dasher

In this post I’ve to share sending email along with html and multiple attachment using php. The sample PHP script.

<?PHP

$from='from@xxx.com';
$to='to@yyy.com';
$subject='Email Subject';
$emailmessage='Email Message';
$attachment_1='testfile1.pdf';
$attachment_2='testfile2.pdf';

$mimeboundary = md5(time());
$eol = PHP_EOL;
// header
$headers  = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol; 
$headers .= "Content-Type: multipart/mixed; boundary="".$mimeboundary.""";

// body
$message = "--".$mimeboundary.$eol;
$message .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$message .= "Email Body.".$eol.$eol;

// message
$message .= "--".$mimeboundary.$eol;
$message .= "Content-Type: text/html; charset="iso-8859-1"".$eol;
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$message .= $emailmessage.$eol.$eol;

// attachment1 
$file = fopen($attachment_1,"rb");
$data = fread($file,filesize($attachment_1));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "--".$mimeboundary.$eol;
$message .= "Content-Type: application/octet-stream; name="".$attachment_1.""".$eol; 
$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment".$eol.$eol;
$message .= $data.$eol;
$message .= "--".$mimeboundary.$eol;

// attachment2
$file = fopen($attachment_2,"rb");
$data = @fread($file1,filesize($attachment_2));
fclose($file);
$data1 = chunk_split(base64_encode($data));
$message .= "--".$mimeboundary.$eol;
$message .= "Content-Type: application/octet-stream; name="".$attachment_2.""".$eol; 
$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment".$eol.$eol;
$message .= $data.$eol;
$message .= "--".$mimeboundary."--"; 

if(mail($to, $subject, $emailMessage, $headers)) {
    echo "OK";
} else {
    echo "ERROR";
}

?>

Leave a Reply

Top