首页 > 解决方案 > 在邮件中添加 PhpSpreadsheet 附件

问题描述

我尝试制作一个 PhpSpreadsheet 文档,然后将他添加到邮件附件中。也许是热,但在 phpSpreadsheet 文档中几个小时后,我什么也没找到。

这是我发送邮件的文件

$name = 'export-sst';
$filename = FileAssociatedPeer::getNewTempFilename($name . '.xlsx"');
$filepath = sfConfig::get('sf_upload_dir') . sfConfig::get('app_sfPropelFileAssocPlugin_temp_dir') . '/' . $filename;

include dirname(__FILE__) . 'template.php';

$mail = new PHPMailerBootstrap();
$mail->initialize();
$mail->setCharset('utf-8');
$mail->setContentType('text/html');

$mail->setMailer('smtp');
$mail->setPort((int) sfConfig::get('app_send_mail_port'));
$mail->setHostname(sfConfig::get('app_send_mail_host'));
$mail->setUsername(sfConfig::get('app_send_mail_username'));
$mail->setPassword(sfConfig::get('app_send_mail_password'));
$mail->setSender('cyril@quarks.pro');
$mail->setFrom('cyril@quarks.pro', 'Logiciel Quarks');

$subject = 'test';

$mail->setSubject($subject);
$body = <<<EOT
Test
EOT;
$mail->setBody(nl2br($body));
$mail->addAddress('test@talala.com');

$mail->addAttachment($spreadsheet, $name . '.xlsx', 'base64', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

$mail->send();

在查看文档后,这里是我的电子表格构造。


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

$spreadsheet = new Spreadsheet();
$active_sheet = $spreadsheet->getActiveSheet();
$active_sheet->setTitle('Tableau général');

$active_sheet->setCellValue('A1', 'Hello World !');
$active_sheet->setCellValue('B1', 'tada');


header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'. $filename .'.xlsx"');
header('Cache-Control: max-age=0');

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');

我在没有 addAttachement 的情况下发送邮件没有问题,但是当我取消注释这一行时,我所有的尝试都会抛出错误。

感谢您的宝贵时间

标签: phpphpmailerphpspreadsheet

解决方案


无法关闭 zip 文件错误表明您对目标文件路径没有正确的权限。

尝试使用绝对路径以确保您拥有正确的路径。

$path = "<Absolut Path>";

//do stuff

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($path); 

推荐阅读