使用php邮件发送php excel作为附件

时间:2017-03-29 17:08:46

标签: php phpmailer phpexcel

我有以下内容:

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_start();
$objWriter->save("php://output");
$xlsData = ob_get_contents();
$xlsData1= "data:application/vnd.ms-excel;base64,".base64_encode($xlsData);
ob_end_clean();


        //Require for mailing functionality
        require_once('../../PHPMailer/PHPMailer-master/class.phpmailer.php');

        //Send mail function
        $mail= new PHPMailer(); // defaults to using php "mail()"
        $sender ="emailadddress";
        $mail->SetFrom($sender);
        $mail->AddAddress('emailaddress');   
        $mail->Subject="Combined repair and production report from ".$reportDate;
        $encoding = "base64"; 
        //$type = "image/png";
        $mail->AddStringAttachment(base64_decode($xlsData1), "combined_report".$reportDate."xlsx");  
        //$mail->AddAttachment($xlsData, $filename);
        $message= "Please see attached combined report";
        $message = "</body></html>";              
        $mail->MsgHTML($message);    

        if(!$mail->Send()) 
        {
            $response =  array(
                'op' => 'failed',
                'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
            );
        } 
        else 
        {
            $response =  array(
                'op' => 'ok',
                'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
            );

        } 





die(json_encode($response));
pg_close($conn);

这会发送一封带有attachemnt的电子邮件,但附件是一个空白文件。当我尝试保存它时,它具有如下文件名和扩展名:&#34; filenamexlsx&#34;所以它看起来没有得到正确的xlsx格式。我也试过这个:

$mail->AddStringAttachment("data:application/vnd.ms-excel;base64,".base64_encode($xlsData);  

我也尝试过:

    $encoding = "base64"; 
    $type = "application/vnd.ms-excel"; // and :application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    $mail->AddStringAttachment(base64_decode($xlsData1), "combined_report".$reportDate."xlsx",$encoding,$type);

我还尝试使用AddAttachment()代替字符串附件,当我这样做时,电子邮件中没有附件。

我跟着:  php send e-mail with attachment

并且还查看了多个内容,例如PHPMailer, AddStringAttachment and Data URI Scheme

但它似乎没有工作:(任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我认为你的文件名有误。您的文件名应为 filename.xlsx ,而不是 filenamexlsx