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!
blog comments powered by Disqus |
|
|
|
|
|
|
|