Skip to content
Advertisement

Attach excel stream to swiftmailer message?

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.

Advertisement

Answer

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)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement