Attaching Dynamic Content

Files that are generated at runtime, such as PDF documents or images created via GD can be attached directly to a message without writing them out to disk. Use the standard Swift_Attachment::newInstance() method.

To attach dynamically created content:

  1. Create your content as you normally would.
  2. Create an attachment with Swift_Attachment::newInstance(), specifying the source data of your content along with a name and the content-type.
  3. Add the attachment to the message with attach().

The attachment will be presented to the recipient as a downloadable file with the filename and content-type you specify.

Note: If you would usually write the file to disk anyway you should just attach it with Swift_Attachment::fromPath() since this will use less memory.
//Create your file contents in the normal way, but don't write them to disk
$data = create_my_pdf_data();

//Create the attachment with your data
$attachment = Swift_Attachment::newInstance($data, 'my-file.pdf', 'application/pdf');  

//Attach it to the message
$message->attach($attachment);


//You can alternatively use method chaining to build the attachment
$attachment = Swift_Attachment::newInstance()
  ->setFilename('my-file.pdf')
  ->setContentType('application/pdf')
  ->setBody($data)
  ;

NOTE: Documentation for version 3 is in the wiki.