繁体   English   中英

将 excel 流附加到 swiftmailer 消息?

[英]Attach excel stream to swiftmailer message?

我正在尝试在 SwiftMailer 消息中附加一个 Excel 文件。

诀窍是我不想保存 excel 文件然后附加它然后删除它,而是我只想生成 excel 并将其附加到消息中。

此函数允许附加一个 OutputByteStream

/**
 * Create a new Attachment.
 *
 * @param string|Swift_OutputByteStream $data
 * @param string                        $filename
 * @param string                        $contentType
 *
 * @return Swift_Mime_Attachment
 */
public static function newInstance($data = null, $filename = null, $contentType = null)
{
    return new self($data, $filename, $contentType);
}

Symfony PHPExcel 包中有一个函数来创建响应

/**
 * Stream the file as Response.
 *
 * @param \PHPExcel_Writer_IWriter $writer
 * @param int                      $status
 * @param array                    $headers
 *
 * @return StreamedResponse
 */
public function createStreamedResponse(\PHPExcel_Writer_IWriter $writer, $status = 200, $headers = array())
{
    return new StreamedResponse(
        function () use ($writer) {
            $writer->save('php://output');
        },
        $status,
        $headers
    );
}

他们似乎在呈现响应时调用该回调,但是如何将 php://output 保存在变量或其他内容中以将其传递给 newInstance 方法?

我尝试传递响应对象 (StreamedResponse) 但它只有标题,我也尝试使用 $response->getContent() 并将 $writer->save('php://output') 传递给 newInstance 方法。

使用 stream_get_contents

$attachment = \Swift_Attachment::newInstance(stream_get_contents(createStreamedResponse(...)), 'test.xls', 'application/vnd.ms-excel');

(不知道你实际的 mimetype 是什么)

我做了这样的伎俩:

首先,我使用输出缓冲并检索输出缓冲区的内容:

    ob_start();
    $writer = new Xlsx($excelFile);
    $writer->save('php://output');
    $data = ob_get_contents();
    ob_end_clean();

然后我检索 $attachment :

$attachment = \Swift_Attachment::newInstance($data, $fileName, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

最后,我将文件附加到邮件中,如 SwiftMailer 文档中所示:

$email->attach($attachment);

使用新的 Symfony Mailer 组件,您可以做到:

//same as @tCot response
ob_start();
$writer = new Xlsx($excelFile);
$writer->save('php://output');
$data = ob_get_contents();
ob_end_clean();

在您的电子邮件声明中:

$email->embed($data, $filename) //The third parameters (mime type) can be guess by Symfony

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM