Introducing Swift Mailer

Do you want to build a complex email program in PHP that offers more control than the language’s native “mail()” function? You may want to consider using the Swift Mailer email library. This multi-part series will walk you through some of its most useful features.

If you’ve been developing web applications with PHP for a while, then you’ll surely know that the language offers a couple of options that allow you to send email messages in a pretty straightforward way. Undoubtedly, the easiest thing to do is to create email scripts by means of the “mail()” native function. That allows you to avoid having to deal directly with the internals of the SMTP protocol itself, thus making the entire creation process much more approachable.

Logically, these benefits come at a cost. The major down side in using this function is the lack of more accurate control as to how emails are sent out, not to mention a few incompatibilities that exist when working with different operating systems.

On the other hand, it’s possible to build email programs by using the functions that come with the PHP socket extension. This is by far a more complex procedure; in that case it’s not only necessary to get a more intimate background in many of the commands supported by the SMTP protocol, but also a solid understanding of how to manipulate TCP sockets.

Of course, this last option is the best one when it comes to developing full-featured email applications — but it offers a steep learning curve that many programmers are reluctant to follow. However, there’s no need to reinvent the wheel each time you need to build this kind of application. There are a few useful third-party email libraries available nowadays that will let you accomplish this in a truly effortless way.

In my personal opinion, one of the best email libraries that can be found today is Swift Mailer, a powerful package developed by Chris Corbin that allows you to  quickly develop email programs. With Swift Mailer, you use a strict object-oriented approach in conjunction with a solid base of dependencies that “talk” directly to SMTP servers.

Indeed, Swift Mailer offers plenty of handy features that permit you to perform all sort of clever tasks when sending email, such as manipulating MIME headers with ease, handling attachments, formatting messages in HTML and much, much more.

Therefore, in this series of articles I’m going to take a deeper look at this library, so you can start using it within your own PHP applications. Of course, this will be only an introductory guide to working with the library’s most relevant features. The best place to look for more thorough documentation is its official user guide, which is also very easy to follow.

Now, it’s time to start leveraging the real power behind Swift Mailer. Let’s go!

{mospagebreak title=Start using Swift Mailer}

Before you make any attempt to start working with Swift Mailer, it’s necessary to download the library from its official web site. Once you’ve done this, and the package has been uncompressed to a folder on the local web server, the only file that needs to be included directly is one called “swift_required.php.” It’s that simple .

The rest of the dependencies required by the library will be automatically loaded by this file, thanks to the handy autoloading capabilities offered by PHP 5.

So far, so good. Assuming that Swift Mailer has been correctly installed on the server, the next step is to build a script that includes the “swift_required.php” file, and then specifies the SMTP transport that will be used to send email.

In this first example, I’m going to use a fictional SMTP server that requires authentication. The script that does this will look like this: 

// include required file

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

As shown above, the script starts including the corresponding “swift_required.php” file, and then creates a transport object with the required mail server domain via the “newInstance()” method of the “Swift_SmtpTransport” class. Finally, the user and password values are passed to the “setUsername()” and “setPassword()” methods respectively, to establish the pertinent connection to the SMTP server.

From the previous script, it’s clear to see that Swift Mailer uses a nice, strict object-oriented approach that includes calls to a factory and chainable method, while keeping the whole code readable and easy to maintain. It’s a beautiful and powerful thing, indeed.

Well, now that an SMTP transport object has been successfully created, we need to build a mailer object and the email message itself, including its subject, body, additional MIME headers and so forth.

But guess what? Swift Mailer will let you do this by using separate classes, thus keeping the complete code modular and loosely coupled. So, in the next section I’m going to explain how to build the mailer and create a simple email message.

To learn the full details, click on the link that appears below and keep reading.

{mospagebreak title=Creating mailer and message objects}

In the previous segment, I discussed how to create a SMTP transport object from the “Swift_SmtpTransport” class provided by Swift Mailer. Now, I"m going to build a brand new mailer object, which will permit us to send a great variety of email messages very easily. After that, I’m going to create another object, which will be responsible for building the different parts of the email message itself.

Having explained that, here’s the code required to perform these tasks. Take a look at it, please:

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

// build the body part of the message

->setBody(‘Hey, how are you? I am sending you a message with the cool Swift Mailer library’);

Definitely, the above script is extremely simple to follow, even if you don’t have a strong background in working with classes and objects. It begins creating a new mailer object by statically calling the factory “newInstance()” method of the “Swift_Mailer” class. Once this process has been completed correctly, a basic email message is built by using a separate class called, not surprisingly, “Swift_Message.”

Again, it’s valid to note here the clever use of the static, chainable factory “newInstance()” method. It returns a message object to client code and allows you to specify certain common parameters of the message, such as the subject, the From and To arguments, and finally the body part.

Well, at this stage I’ve explained in a step-by-step fashion how to create the different objects required by Swift Mailer to send a simple email message. However, the best way to understand how this process is performed is by putting all of the pieces together in the same script.

With that idea in mind, below I listed the complete script. It first builds the SMTP transport object, then creates the corresponding mailer, and finally composes the message with the proper arguments. Here it is:

// include required file

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

// build the body part of the message

->setBody(‘Hey, how are you? I am sending you a message with the cool Swift Mailer library’);

I don’t want to sound a bit over-excited here, but things are definitely becoming much more interesting now. Everything has been set up to send a basic email message with Swift Mailer. However, there’s something missing yet; it’s necessary to call a method of the mailer object that actually dispatches the message in question.

Not surprisingly, this method has been called “send(),” and in the last section of this tutorial I’m going to discuss how to use it in conjunction with the script developed before.

Now, to find out how to send email messages with this new method, click on the link below and read the next few lines.

{mospagebreak title=Sending an email message with the send() method}

As you’ll recall from the previous section, the only step that remains to send the email message with Swift Mailer is calling the “send()” method that belongs to the “Swift_Mailer” class.

To illustrate how to perform this task as clearly as possible, I’ve included the complete source code of the script developed in the segment that you just read, along with the code block that actually sends out the message. Look at it, please:

// include required file

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

// build the body part of the message

->setBody(‘Hey, how are you? I am sending you a message with the cool Swift Mailer library’);

 

// send the email message

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

{

echo ‘The message was sent successfully!’;

}

else

{

echo ‘Error sending email message’;

}

Certainly, you’ll have to agree with me that using the “send()” method is a straightforward process. It accepts as an input argument the $message object created before and dispatches the actual message according to the supplied parameters. If this operation fails for whatever reason, the method will return a value of FALSE, as shown clearly in the above code sample.

And finally, with this example I’m finishing up this introductory tutorial on using the Swift Mailer library. As you saw through the basic example developed previously, sending email with this package is a well-structured process that demonstrates proven software design principles, such as object aggregation, method chaining and the Factory pattern.

Final thoughts

In this first chapter of the series, I introduced you to working with the Swift Mailer library. Speaking more specifically, in this tutorial you learned how to create SMTP transport, mailer and message objects, which are required to send out email.

However, I’m only scratching the surface of the numerous features offered by Swift Mailer. In the next article I’m going to explain how to send email messages by using a local SMTP server and the “sendmail” Unix application.

So, my final advice is simple: don’t miss the next part!

Google+ Comments

Google+ Comments