在php邮件功能中发送多个附件文件

时间:2014-08-05 06:00:26

标签: php email-attachments

我有一些代码可以通过php中的邮件功能发送多个附件。 如果只有一个附件,将发送带附件的邮件。 但是,如果在阵列中添加两个或更多文件,邮件发送将失败。 这是我的代码

// array with filenames to be sent as attachment
//$files = array("upload/Tulip.jpg");
$files = array("upload/Tulip.jpg","upload/Tulips.jpg","upload/Tulips1.jpg");

// email fields: to, from, subject, and so on
    $to = "mail@mail.com";
    $from = "mail@mail.com"; 
$subject ="My subject"; 
$message = "My message";
$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";

// preparing attachments
for($x=0;$x<count($files);$x++){
    $file = fopen($files[$x],"rb");
    $data = fread($file,filesize($files[$x]));
    fclose($file);
    $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";
}

$ok = @mail($to, $subject, $message, $headers); 
if ($ok) { 
    echo "<p>mail sent to $to!</p>"; 
} else { 
    echo "<p>mail could not be sent!</p>"; 
} 

如果$ files数组只有一个文件,将发送邮件。 请有人帮我解决这个问题。 请记住,如果$ files数组中只有一个图像路径,上面的代码可以正常工作。

提前致谢

0 个答案:

没有答案