It's possible you haven't read the first chapter of this series, where I showed how to use the Swift Mailer library to send a simple email message by means of a remote SMTP server that required authentication. Therefore, below I reintroduced the script developed in that tutorial. It not only describes in a step-by-step fashion how to dispatch emails, but how to use a specific SMTP transport.
Having said that, here's the entire source code corresponding to the script in question. Take a look at it, please:
// include required file
// create the mail transport using the 'newInstance()' method
$transport = Swift_SmtpTransport::newInstance('mail.domain.com', 25)
// 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('email@example.com' => 'Alejandro Gervasio'))
// specify the To argument
->setTo(array('firstname.lastname@example.org' =>' 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
echo 'The message was sent successfully!';
echo 'Error sending email message';
If you closely examine the above example, you'll realize that my opinions on the way that Swift Mailer does its thing aren't unfounded. As shown above, the steps required for sending an email message are extremely well-differentiated. They consist of creating the proper SMTP transport (in this particular case, a remote server that uses authentication), building a mailer object, and finally assembling the different parts of the message, which is sent via the "send()" method.
As I expressed in the introduction, the library correctly implements the Factory pattern when using the "newInstance()" method associated with each involved class. This permits you to chain different methods very easily, thus making the code much more compact.
Having reintroduced the example created in the first article of the series, it's time to explore other useful features offered by Swift Mailer. So, as I explained at the beginning, the library allows you to send email by using different SMTP transports, either from local or remote servers. Of course, you already learned how to perform this process with a remote host, so in the following section I'm going to discuss how to create a transport based on a local server.
Please read the segment to come. I'll be there, waiting for you.
blog comments powered by Disqus