Sending Email With Multiple Attachments in PHP » Best Tested and Working Code
This script is really helpful for those who want to send email with multiple attachments in PHP. There are scripts out there but most of them have some errors in them but i assure you that this script is error free.
If you guys face any error please let me know and i will try my best to assist you.
<?php
function SendAttachMail($to,$from,$sub,$msg,$i)
{
$flag_attach = true;
$email_from = $from;
$email_subject = $sub;
$email_txt = $msg;
$headers = "From: $email_from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
"boundary=\"{$mime_boundary}\"";
$email_message .= "This is a multi-partmessage in MIME
format.\n\n" . "--{$mime_boundary}\n" .
"Content-Type:text/html; " .
"charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $email_txt . "\n\n";
$fileatt_type = "application/octet-stream";
$fileatt = $_FILES['fileatt'.$i]['tmp_name'];
$fileatt_type = $_FILES['fileatt'.$i]['type'];
$fileatt_name = $_FILES['fileatt'.$i]['name'];
$file = fopen($fileatt,"rb");
$data = fread($file,filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$email_message = $email_message.$email_txt;
@mail($to, $email_subject, $email_message, $headers);
}
if(isset($_POST['cmdsend']))
{
$to="to@gmail.com";
$from="from@gmail.com";
$sub=$_POST['em_sub'];
$msg=$_POST['em_msg'];
for($i=1; $i<=3; $i++)
{
$file_name=$_FILES['fileatt'.$i]['name'];
if(trim($file_name)!='')
{
SendAttachMail($to,$from,$sub,$msg,$i);
}
}
}
?>
<form name="frmemail" enctype="multipart/form-data" method="post" action="">
Enter Subject: <input type="textbox" name="em_sub">
Enter Email Message: <input type="textbox" name="em_msg">
Attach File1: <input type="file" name="fileatt1">
Attach File2: <input type="file" name="fileatt2">
Attach File3: <input type="file" name="fileatt3">
<input type="submit" name="cmdsend" value="Send Email">
</form>