PHP code for sending an email with multiple file attachment

In the earlier post we have seen about sending an email with a file attachment .

PHP code for sending an email with file attachment

Now let us see how to send an a email with multiple file attachment.

For this just we have to place the files in an array
$files=array(file1.PDF, file2.PDF);

Let us see code for sending an email with multiple file attachments

$to =;
$from =;
$subject = “Email with multiple file attachment”
$message = “Refer the attached files”;
$headers = “From: $from”;

// boundary
$semi_rand = md5(time());
$mime_boundary = “==Multipart_Boundary_x{$semi_rand}x”;

// headers for attachment
$headers .= “\nMIME-Version: 1.0\n” . “Content-Type: multipart/mixed;\n” . ” boundary=\”{$mime_boundary}\””;

// multipart boundary
$message = “This is a multi-part message in MIME format.\n\n” . “–{$mime_boundary}\n” . “Content-Type: text/plain; charset=\”iso-8859-1\”\n” . “Content-Transfer-Encoding: 7bit\n\n” . $message . “\n\n”;
$message .= “–{$mime_boundary}\n”;

//Files for attachment
$files=array(file1.PDF, file2.PDF);

// preparing attachments
for($x=0;$x $my_path = $_SERVER[‘DOCUMENT_ROOT’].”/myfiles/”;
$file = fopen($my_path.$files[$x],”rb”);
$data = fread($file,filesize($my_path.$files[$x]));
$data = chunk_split(base64_encode($data));
$message .= “Content-Type: {\”application/octet-stream\”};\n” . ” name=\”$files[x]\”\n”.”Content-Disposition: attachment;\n” . ” filename=\”$files[x]\”\n”.”Content-Transfer-Encoding: base64\n\n” . $data . “\n\n”;
$message .= “–{$mime_boundary}\n”;

//now use the mail function to send email
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo “mail send … OK”;
} else {
echo “mail send … ERROR!”;

Using this you can also send the different types of document

eg: $files=array($file1.TXT, $file2.PDF,$file3.CSV)

Posted in Php Tagged with: ,