Dynamically Attaching Files with Swift Mailer

In this eighth part of a ten-part series on the Swift Mailer email library, you’ll learn how to attach files that have been dynamically generated to an email message. In addition, you’ll see how to use Swift Mailer’s “setFileName()” method to modify the name of an attachment before it’s sent, which speaks for itself about this library’s flexibility.

In case you haven’t heard about it yet, Swift Mailer is a comprehensive library written in PHP 5 and freely available at http://swiftmailer.org. It allows you to develop email applications very quickly and with minor effort, through a cohesive and highly intuitive programming interface.

So, if you’re a PHP developer interested in taking advantage of the most relevant features provided by this solid email package, or simply want to take a quick look at what it can do for you, then start reading this series of articles right now!

Being one of the most powerful email packages available nowadays that really uses a strict object-oriented approach and a correct implementation of some popular design patterns, Swift Mailer will let you perform all sorts of clever tasks when building email programs with PHP. These include sending email messages in HTML, handling inline attachments, manipulating MIME headers with ease, and so forth.

And now that I’ve talked about handling attachments with Swift Mailer, I left off the last tutorial discussing how to use the “Swift_Attachment” class included with the library to attach a single file to an email message first from a local server, and then from a remote host.

Thanks to the intrinsic flexibility given by the “fromPath()” method that belongs to the handy “Swift_Attachment” class, not only is it possible to perform these tasks with attachments, but it’s also feasible to achieve even more useful things with them, such as changing their names on the fly or embedding a dynamically-generated file into an email message.

Sounds pretty interesting, right? So, in this eighth part of the series I’m going to explain, as usual with a decent number of code samples, how to perform the previous attachment operations in a few simple steps.

Are you ready to keep learning more about the Swift Mailer library? Then click on the link below and read the next lines!

{mospagebreak title=Review: handling attachments with Swift Mailer}

Before I proceed to explain how to use Swift Mailer to attach files that have been generated dynamically, I’m going to reintroduce the example developed in the previous tutorial of this series. It demonstrated how to attach an image file to an email message from a local server, and a remote host as well.

Having stated that, here’s the first example. It uses a local host to attach the image.

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

 

// 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’)

->attach(Swift_Attachment::fromPath(‘path/to/file/image1.jpg’));

 

// send the email message

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

{

echo ‘The message was sent successfully!’;

}

else

{

echo ‘Error sending email message’;

}

The above script is very easy to follow. All it does is attach an image file to an email message from a specified location on the local server. Once this operation has been performed successfully, the message is sent out via the already familiar “send()” method. It’s simple to code and read, indeed.

Now, moving forward, take a look at the second example, which does nearly the same thing as the previous one. In this case, however, the image file is attached from a remote URL. Here it is:

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

 

// 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’)

->attach(Swift_Attachment::fromPath(‘http://www.domain.com/images/image1.jpg’));

 

// send the email message

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

{

echo ‘The message was sent successfully!’;

}

else

{

echo ‘Error sending email message’;

}

As I said before, in this case the file being attached to the message is retrieved from a fictional remote host, thus demonstrating the remarkable flexibility offered by the “fromPath()” method of the “Swift_Attachment” class, especially when attaching files from different locations.

So far, so good. At this stage, I’m sure that you quickly grasped how the two previous scripts work, so it’s time to explore other handy capabilities of the Swift Mailer library. Therefore, in the following section I’m going to discuss how to use the aforementioned “fromPath()” method for attaching a file that has been created dynamically.

To learn how this will be done, please click on the link below and read the next segment.

{mospagebreak title=Attaching dynamically-generated files}

As you know, there are cases where it’s necessary to attach a file that has been created dynamically to an email message, usually through a PHP server-side graphic library such as GD or via a custom function or class. Fortunately, Swift Mailer supports this requirement; its “fromPath()” method can take a file generated like this and annex it to an existing message.

To demonstrate this ability, below I modified the script built in the previous section, which simulates the situation described above. Look at it:

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

 

// 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’;

}

Even though at first sight the above script looks very similar to the one that you saw in the previous section, it actually performs a different task. It attaches a dynamic PNG file that has been hypothetically created with the GD PHP library.

This file in question is then passed directly to the “newInstance()” method of the pertinent “Swift_Attachment” class, where it’s finally attached to the email message. Not too difficult to understand, right?

Please don’t get me wrong; I don’t want to sound like I’m marketing the Swift Mailer library to you, but it definitely makes handling attachments a no-brainer process. However, I’d like to finish this tutorial by showing you yet another example; it will demonstrate how to change, on the fly, the name of a file being attached.

To see how this last example will be created, read the next section. It’s only one click away.

{mospagebreak title=Dynamically changing the name of an attachment}

As I said in the section that you just read, Swift Mailer permits you to dynamically change the name of a file being attached to an email message. But, how can this be done? Well, as you might have guessed, the library has another handy method called “setFileName()” that will perform this process in a simple manner.

Obviously, the use of this method can be better understood by means of an example. So, bearing this idea in mind, below I coded a pretty simple one for you. Check it out:

// 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’)

->attach(Swift_Attachment::fromPath(‘/image1.jpg’)->setFileName(‘otherimage.jpg’));

 

// send the email message

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

{

echo ‘The message was sent successfully!’;

}

else

{

echo ‘Error sending email message’;

}

That was quite easy to accomplish, right? As you can see, the aforementioned “setFileName()” method permits you to easily modify the name of a file being attached, before sending an email message. While this process may not be a substantial or critical improvement within the previous script, it does show that something as simple as changing the name of an attachment can be done through an elegant and tight programming interface.

And unfortunately, with this last example I’m coming to the end of this article. As always, I encourage you to edit all of the code samples shown in it, so you can see for yourself how simple it is to handle attachments with Swift Mailer.

Final thoughts

In this eighth chapter of the series, you learned how to attach files that have been dynamically generated to an email message. In addition, you saw how to use the “setFileName()” method included with Swift Mailer to modify the name of an attachment before it is sent, which speaks for itself about the flexibility offered by this library.

In the upcoming tutorial, I’m going to teach you how to embed attached files into messages by manipulating the “Content-disposition” MIME header. Thus, now that you know what to expect from the next part, you simply can’t miss it!

Google+ Comments

Google+ Comments