Chapter 17. Sending Email

Most of your interaction with users will be via web pages, but sending or receiving an email message every now and then is useful, too. Email is a great way send updates, order confirmations, and links that let users reset their passwords.

This chapter explains the basics of using the Swift Mailer library to send email messages.

Swift Mailer

First, use Composer to install Swift Mailer:

php composer.phar require swiftmailer/swiftmailer

As long as you’ve got the standard require "vendor/autoload.php"; statement in your program, Swift Mailer is now available to use.

Swift Mailer represents messages as Swift_Message objects. To create an email message, you create one of these objects and then call methods on it to build the message. Then you hand the message object to an instance of the Swift_Mailer class so that the message can be sent. The Swift_Mailer instance, in turn, is configured with a particular kind of Swift_Transport class. This transport class embodies the logic of how the message is actually sent—either by connecting to a remote server or by using mail utilities on the local server.

Example 17-1 creates a simple email message with a subject, from address, to address, and plain-text body.

Example 17-1. Creating an email message
$message = Swift_Message::newInstance();
$message->setFrom('julia@example.com');
$message->setTo(array('james@example.com' => 'James Bard'));
$message->setSubject('Delicious New Recipe');
$message->setBody(<<<_TEXT_ ...

Get Learning PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.