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