Embedding Dynamic Content

Images that are generated at runtime, such as images created via GD can be embedded directly to a message without writing them out to disk. Use the standard Swift_Image::newInstance() method.

To embed dynamically created content:

  1. Create a message object with Swift_Message::newInstance().
  2. Set the body as HTML, and embed a file at the correct point in the message with embed(). You will need to specify a filename and a content-type.

The file will be displayed with the message inline with the HTML wherever its ID is used as a src attribute.

Note: Swift_Image and Swift_EmbeddedFile are just aliases of one another. Swift_Image exists for semantic purposes.
Note: You can embed files in two stages if you prefer. Just capture the return value of embed() in a variable and use that as the src attribute.
//Create your file contents in the normal way, but don't write them to disk
$img_data = create_my_image_data();

//Create the message
$message = Swift_Message::newInstance('My subject');

//Set the body
$message->setBody(
'<html>' .
' <head></head>' .
' <body>' .
'  Here is an image <img src="' . //Embed the file
     $message->embed(Swift_Image::newInstance($img_data, 'image.jpg', 'image/jpeg')) .
   '" alt="Image" />' .
'  Rest of message' .
' </body>' .
'</html>',
  'text/html' //Mark the content-type as HTML
);


// If placing the embed() code inline becomes cumbersome
// it's easy to do this in two steps
$cid = $message->embed(Swift_Image::newInstance($img_data, 'image.jpg', 'image/jpeg'));

$message->setBody(
'<html>' .
' <head></head>' .
' <body>' .
'  Here is an image <img src="' . $cid . '" alt="Image" />' .
'  Rest of message' .
' </body>' .
'</html>',
  'text/html' //Mark the content-type as HTML
);

NOTE: Documentation for version 3 is in the wiki.