Skip to Content
Learning PHP
book

Learning PHP

by David Sklar
April 2016
Beginner content levelBeginner
550 pages
9h 40m
English
O'Reilly Media, Inc.
Content preview from Learning PHP

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_
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning PHP 5

Learning PHP 5

David Sklar
Learning PHP 7

Learning PHP 7

Antonio L Zapata (GBP)
Advanced PHP Programming

Advanced PHP Programming

George Schlossnagle

Publisher Resources

ISBN: 9781491933565Errata PageSupplemental Content