通过php mail()发送的Excel附件已损坏

时间:2014-04-22 10:12:07

标签: php email-attachments

使用以下代码将Excel文件作为附件发送。

<?php 
ini_set ("SMTP","smtp.smpt.com");
ini_set ("sendmail_from","from.com");
$date=date("l jS \of F Y");
$to  = 'my mail id'; 
$from = 'from mail id'; 
$replyto  = 'from mail id'; 
$fileatt="zxxxxxyyyyyy.xls";
$subject = 'Tran Data Rejects as of ' .$date; 
$message= "Hi Team, Please find the attached file having Tran Data Rejects as of today Thanks,     EDW Support";
     $flags = 'style="display:none;"';
     $attachment = chunk_split(base64_encode(file_get_contents($fileatt)));
     $filename = $fileatt;
     $boundary =md5(date('r', time())); 
     $headers = "From: from mail\r\nReply-To: from mail";
     $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed;     boundary=\"_1_$boundary\"";
         $message="This is a multi-part message in MIME format.
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
$message
--_2_$boundary--
--_1_$boundary
Content-Type: application/vnd.ms-excel; name=\"$filename\" 
Content-Transfer-Encoding: binary
Content-Disposition: attachment 
$attachment
--_1_$boundary--";
     mail($to, $subject, $message, $headers);
?>

问题是我在邮件中收到的附件损坏如下 -

Content-Transfer-Encoding: binary
Content-Disposition: attachment 

0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAAQAAAAAAAAAA
EAAAWgAAAAEAAAD+////AAAAAAAAAAD/////////////////////////////////////////////
////////////////////////////////////////////////////////////9
////WQAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8A
AAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAA
AB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACQAAAAlAAAAJgAAACcAAAAoAAAAKQAAACoAAAArAAAA
LAAAAC0AAAAuAAAALwAAADAAAAAxAAAAMgAAADMAAAA0AAAANQAAADYAAAA3AAAAOAAAADkAAAA6
AAAAOwAAADwAAAA9AAAAPgAAAD8AAABAAAAAQQAAAEIAAABDAAAARAAAAEUAAABGAAAARwAAAEgA
AABJAAAASgAAAEsAAABMAAAATQAAAE4AAABPAAAAUAAAAFEAAABSAAAAUwAAAFQAAABVAAAAVgAA

你们可以帮我纠正一下代码:(

1 个答案:

答案 0 :(得分:0)

尝试使用mail_attachment功能

$ mypath = excel文件的路径

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers.= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// and your addition code here
mail_attachment($email_from, $email_to, $email_subject, $email_message ,$my_path);