Attach excel stream to swiftmailer message?

≯℡__Kan透↙ 提交于 2021-02-09 17:53:51

问题


I'm trying to attach an Excel file in a SwiftMailer message.

The trick is that I don't want to save the excel file and then attach it and then delete it, instead I just want to generate the excel and attach that to the message.

This function allows to attach a 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);
}

There is a function in Symfony PHPExcel bundle to create the response

/**
 * 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
    );
}

They seems to call to that callback when they are rendering the reponse, but How can I save the php://output in a variable or something to pass it to newInstance method?

I tried passing the response object (StreamedResponse) but it only have the headers, I also tried with $response->getContent() and passing $writer->save('php://output') to newInstance method.


回答1:


use stream_get_contents

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

(dont know hat your actual mimetype is)




回答2:


I made the trick like this :

Firstly, I use the output buffering and retrieve the content of the output buffer :

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

Then I retrieve the $attachement :

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

Finally I attach the file to the mail like in the SwiftMailer documentation :

$email->attach($attachment);



回答3:


With the new Symfony Mailer component you can do that :

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

And in your email declaration :

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


来源:https://stackoverflow.com/questions/43833370/attach-excel-stream-to-swiftmailer-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!