Login

Embedding Attachments into Email Messages with Swift Mailer

In this ninth part of a ten-part series, you’ll learn how to use a couple of methods provided by Swift Mailer to directly embed attachments into email messages. These can be very helpful when sending newsletters that contain numerous images, which you don’t want to be filtered and discarded by popular web-based email systems such as Hotmail and Yahoo.

Among the huge variety of email libraries written in PHP 5, there’s one that stands out from the rest due to its well-structured programming interface, strict use of the object-oriented paradigm, and (if all of these features aren’t good enough for you), its incredibly flat learning curve.

Of course, as you might have guessed from this article’s title, I’m speaking specifically of Swift Mailer. It’s a powerful package that you can download freely at http://swiftmailer.org that will let you build complex email applications in a few simple steps. You’ll make use of its intuitive API and clever implementation of some key concepts applied to software development, such as design patterns and object aggregation.

Naturally, this isn’t breaking news for you if you’ve read the previous articles in this series. In them, I explored the most relevant features offered by Swift Mailer, including its ability to send email messages formatted in HTML, as well as its capacity for attaching files from multiple locations on local hosts and remote servers.

Nevertheless, at this point I’m only scratching the surface when it comes to demonstrating Swift Mailer’s impressive capabilities for handling attachments. You see, so far, all of the examples developed in the previous parts of the series showed how to annex files to an email message by assigning an “attachment” value to the “Content-disposition” MIME header, which works well. But there are cases where this might not be good enough.

For example, what if you need to embed a bunch of images directly into a message? Say you’re sending a newsletter and you want to make it much more appealing to your web site’s visitors. This is a good but scary question, isn’t it? Fear not, because Swift Mailer permits you to manipulate MIME headers in a straightforward fashion, thus allowing you to embed files directly into emails very easily.

So, in the next few lines I’m going to explain in depth how to use embedded attachments with the Swift Mailer library, which will hopefully be an instructive experience for you. Let’s get going!

Just in case you haven’t read the prior tutorial of this series, where I discussed how to attach a dynamically generated file to an email message, below I included the two sample scripts developed in that article. They show how to perform this task in a simple manner, in addition to illustrating how to change on the fly the name of the file.

So, first, here’s the example that attaches a dynamic image to a trivial message:

// include required files

require_once ‘lib/swift_required.php’;

// create the mail transport using the ‘newInstance()’ method

$transport = Swift_SmtpTransport::newInstance(‘mail.domain.com’, 25)

->setUsername(‘alejandro@domain.com’)

->setPassword(‘password’);

// create the mailer using the ‘newInstance()’ method

$mailer = Swift_Mailer::newInstance($transport);

// create a simple message using the ‘newInstance()’ method

// $image has been generated previously using for instance the GD library or a similar package

$message = Swift_Message::newInstance()

// specify the subject of the message

->setSubject(‘Testing Swift Mailer’)

// specify the From argument

->setFrom(array(‘alejandro@domain.com’ => ‘Alejandro Gervasio’))

// specify the To argument

->setTo(array(‘john@domain.com’ =>’ John Doe’))

->setCc(array(‘mary@domain.com’ => ‘Mary Jackson’))

->setBcc(array(‘susan@domain.com’ => ‘Susan Norton’))

// build the body part of the message

->setBody(‘Hey, how are you? I am sending you a message with the cool Swift Mailer library. Make sure to check the attached file!’)

->addPart(‘<p>This part of the message has been formatted as HTML to make it look nicer</p>’, ‘text/html’)

->attach(Swift_Attachment::newInstance($image, ‘sample_image.png’));

// send the email message

if ($mailer->send($message))

{

echo ‘The message was sent successfully!’;

}

else

{

echo ‘Error sending email message’;

}

From the above code sample, it’s clear to see how easy it is to attach an image that has been created with a server-side library to an email message, thanks to the flexibility provided by the “newInstance()” method that belongs to the “Swift_Attachment” class. In this particular case the $image variable would hold the image in question, which has been generated as a PNG graphic.

Now, moving forward, it’s time to look at the second example that shows how to modify the name of an attachment. This time we use another handy method of Swift Mailer, not surprisingly called “setFileName().”

Here’s how this example looks:

// example on sending a basic email message with Swift Mailer (uses the ‘addPart()’ method and Swift_Attachment class and the setFileName() method)

// include required files

require_once ‘lib/swift_required.php’;

// create the mail transport using the ‘newInstance()’ method

$transport = Swift_SmtpTransport::newInstance(‘mail.domain.com’, 25)

->setUsername(‘alejandro@domain.com’)

->setPassword(‘password’);

// create the mailer using the ‘newInstance()’ method

$mailer = Swift_Mailer::newInstance($transport);

// create a simple message using the ‘newInstance()’ method

$message = Swift_Message::newInstance()

// specify the subject of the message

->setSubject(‘Testing Swift Mailer’)

// specify the From argument

->setFrom(array(‘alejandro@domain.com’ => ‘Alejandro Gervasio’))

// specify the To argument

->setTo(array(‘john@domain.com’ =>’ John Doe’))

->setCc(array(‘mary@domain.com’ => ‘Mary Jackson’))

->setBcc(array(‘susan@domain.com’ => ‘Susan Norton’))

// build the body part of the message

->setBody(‘Hey, how are you? I am sending you a message with the cool Swift Mailer library. Make sure to check the attached file!’)

->addPart(‘<p>This part of the message has been formatted as HTML to make it look nicer</p>’, ‘text/html’)

Nothing really spectacular is happening here, right? As shown before, the “setFileName()” method allows you to change the default name of an attached file dynamically, before sending the email message via the corresponding “send()” method. It’s that simple, really.

Well, at this point you hopefully understand how these two scripts do their business, so it’s time to dig deeper into the capabilities offered by Swift Mailer to manipulate attachments in different ways.

In the following section I’m going to demonstrate how to directly embed those attachments into an email message, first by using one new method called “setDisposition()” and finally by means of another one, named simply “embed().”

To learn how the first of these methods can be used, jump ahead and read the next segment. It’s only one click away.

{mospagebreak title=Working with inline attachments with the setDisposition() method}

Until now, all of the scripts that worked with attachments used by default the “Content-disposition: attachment” MIME header to annex a file to the message being sent. However, as you may know, the SMTP protocol permits you to handle inline attachments very easily, which has been taken into account by the Swift Mailer development team as well.

The library provides basically two ways of embedding files into messages. Both use methods that belong to different classes. The first option comes with the “setDisposition()” method, which is available within the “Swift_Attachment” class, while the second choice is the “embed()” method, which is included with the “Swift_Message” class.

Does this sound a bit confusing to you? Well, to clear things up, let me start by showing you a script that uses the “setDisposition()” method to embed an image file into an email message. Take a look at it:

// example on sending a basic email message with Swift Mailer (uses the ‘addPart()’ method, the Swift_Attachment class and the setDisposition() method)

// include required files

require_once ‘lib/swift_required.php’;

// create the mail transport using the ‘newInstance()’ method

$transport = Swift_SmtpTransport::newInstance(‘mail.domain.com’, 25)

->setUsername(‘alejandro@domain.com’)

->setPassword(‘password’);

// create the mailer using the ‘newInstance()’ method

$mailer = Swift_Mailer::newInstance($transport);

// create a simple message using the ‘newInstance()’ method

$message = Swift_Message::newInstance()

// specify the subject of the message

->setSubject(‘Testing Swift Mailer’)

// specify the From argument

->setFrom(array(‘alejandro@domain.com’ => ‘Alejandro Gervasio’))

// specify the To argument

->setTo(array(‘john@domain.com’ =>’ John Doe’))

->setCc(array(‘mary@domain.com’ => ‘Mary Jackson’))

->setBcc(array(‘susan@domain.com’ => ‘Susan Norton’))

// build the body part of the message

->setBody(‘Hey, how are you? I am sending you a message with the cool Swift Mailer library. Make sure to check the attached file!’)

->addPart(‘<p>This part of the message has been formatted as HTML to make it look nicer</p>’, ‘text/html’)

See how simple is to work with inline attachments? This process requires only that a value of "inline" be passed to the corresponding “setDisposition()” method before sending the message to the specified recipients.

The rest of the script remains practically the same, so I’m not going to waste your time with pointless explanations. Instead, now that you’ve learned the first option for working with an inline attachment, in the following section I’m going to demonstrate how to embed the same image file into a message using the previously mentioned “embed()” method.

Now, click on the link below and read the next segment. We’re almost finished!

{mospagebreak title=Introducing the embed() method}

As I expressed in the section that you just read, there’s another method included with Swift Mailer that allows you to insert files into an email message. It’s called “embed().” This one is extremely intuitive. A concrete example that shows how to use it has been coded below.

As depicted above, a sample image file has been inserted directly into a message formatted in HTML via the “embed()” method. For example purposes, I decided to use an instance of the brand new “Swift_Image” class to embed a JPG image within the message’s markup, but naturally it’s also possible to utilize other file types and obtain the same result.

And with this last example I’m finishing up this ninth tutorial exploring the Swift Mailer library. As always, feel free to tweak the code of all the examples developed in this article, so you can get a more solid background in working with inline attachments.

Final thoughts

That’s all for now. In this ninth installment of the series I taught you how to use a couple of methods provided by Swift Mailer, which allow you to directly embed attachments into email messages. These can be very helpful, particularly when sending newsletters that contain numerous images which you don’t want to be filtered and discarded by popular web-based email systems such as Hotmail and Yahoo.

In the final tutorial I’m going to explore another method of the library called “batchSend(),” which allows you to send email messages in a subtly different way.