Embedding Existing Files

Files that already exist, either on disk or at a URL can be embedded in a message with just one line of code, using Swift_EmbeddedFile::fromPath().

You can embed files that exist locally, or if your PHP installation has allow_url_fopen turned on you can embed files from other websites.

To embed an existing file:

  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().

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 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::fromPath('image.png')) .
   '" alt="Image" />' .
'  Rest of message' .
' </body>' .
'</html>',
  'text/html' //Mark the content-type as HTML
);
  

//You can embed files from a URL if allow_url_fopen is on in php.ini
$message->setBody(
'<html>' .
' <head></head>' .
' <body>' .
'  Here is an image <img src="' .
     $message->embed(Swift_Image::fromPath('http://site.tld/logo.png')) .
   '" alt="Image" />' .
'  Rest of message' .
' </body>' .
'</html>',
  'text/html'
);


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

$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.