在PHP中发送多个word文档作为附件

时间:2012-02-05 02:20:57

标签: php

我有一个功能,可以发送一封包含多个word文档作为附件的电子邮件。唯一的问题是,无论我发送多少文档,只有1个显示在电子邮件中,而且,它显示为已损坏。文件路径名是正确的,我已经测试了这个,但是当我尝试从电子邮件中打开文档时,Microsoft word会抱怨文件损坏。有人请告诉我我做错了什么?

function mail_attachment_multiple($to, $subject, $message, $attachment, $from){//sends email as an attachment. attachment parameter is the path to file

$fileatt_type = "application/msword"; // File Type
$email_from = $from; // Who the email is from
$email_subject =  $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to
$headers = "From: ".$email_from;
$msg_txt="\n\n You have recieved a new attachment message from $from";

$email_message = ""; 

//loop through array: $key = filename; $value = filenamePATH
foreach($attachment as $key => $value){
    $fileatt_name = $key; //name of file
    $fileatt_path = $value; // file path (http://www.example.com/filePath)

    $file = fopen($fileatt_path,'rb');
        $temp = get_headers($fileatt_path, 1);
    $file_size = $temp['Content-Length'];           
    $data = fread($file, $file_size); //filesize($fileatt_path)
    fclose($file);

    $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_txt .= $msg_txt;
    $email_message .= "This is a multi-part message 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";
    $data[$key] = 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_path}\"\n" .
              "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" ."--{$mime_boundary}--\n";
}

return @mail($email_to, $email_subject, $email_message, $headers);?>

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你应该真的使用邮件库来做这类事情。我强烈推荐SwiftMailer