On August 19, 2021, Fabien Potencier officially announced the end of maintenance for Swiftmailer. Swiftmailer is being replaced by the symfony/mailer package.

Because of the name, you might think this package can only be used inside a Symfony project, but that's not the case. The naming only implies the package is created by Symfony. So let's take a look at this package and how we can use it inside a project without any framework.

Introducing the components

To email a recipient you need three things; a mailer service, a transporter and, (of course) a message.

Mailer

As you might expect, the symfony/mailer package provides a MailerInterface with a corresponding Mailer service. The Mailer service contains the main API and is responsible for sending the message to the appropriate receiver. The interface only has one method: send(). So the API is very basic and easy to understand. To set up the mailer service a transporter is required.

Transporter

A transporter is responsible for actually sending a message using a particular protocol. The service must implement the TransporterInterface, which also only contains a send() method. When you call the Mailer::send() method, it will delegate this request to the provided TransportInterface::send() method.

Because there are many ways a mail can be sent, there are also many transporters available. By default, this package includes the two most common transporters: sendmail and smtp. There are however many 3rd party transport services available. A full list of these services can be found on the documentation site.

Message

The most important part of sending a message is of course the message itself. Symfony Mailer uses the symfony/mime package. This package provides a few handy objects for creating messages that follow the MIME standard. One of these classes is Email, which provides a high-level API to quickly create an email message. An Email is a data object that contains the message, the recipient, and any other useful headers. This class is also Serializable.

Usage

Now that we are familiar with the underlying components, let's create a PHP program that sends an email via the sendmail protocol.

We'll create a new project by making an empty folder and running the following command inside it:

composer init -n --name symfony-mailer-test

This will create a tiny composer.json file with the following content:

{
"name": "symfony-mailer-test",
"require": {}
}

To use symfony/mailer inside our project, we need to require it:

composer require symfony/mailer

Now we'll create an index.php file, and require the vendor/autoload.php file.

1require_once 'vendor/autoload.php';

Now we'll create the email message we want to send.

1use Symfony\Component\Mime\Email;
2 
3require_once 'vendor/autoload.php';
4 
5$email = (new Email())
6 ->from('[email protected]')
8 ->priority(Email::PRIORITY_HIGHEST)
9 ->subject('My first mail using Symfony Mailer')
10 ->text('This is an important message!')
11 ->html('<strong>This is an important message!</strong>');

As you may notice, the API for creating an Email is very verbose and easy to understand. You might have noticed we provided the content twice; as text and as HTML. When the email client used to read the mail supports HTML, it will show that version, otherwise it will fall back to the text only version.

Now that our Email is done. We can add our transport service and the mailer instance.

1use Symfony\Component\Mailer\Mailer;
2use Symfony\Component\Mailer\Transport\SendmailTransport;
3use Symfony\Component\Mime\Email;
4 
5require_once 'vendor/autoload.php';
6 
7$transport = new SendmailTransport();
8$mailer = new Mailer($transport);
9 
10$email = (new Email())
11 ->from('[email protected]')
13 ->priority(Email::PRIORITY_HIGHEST)
14 ->subject('My first mail using Symfony Mailer')
15 ->text('This is an important message!')
16 ->html('<strong>This is an important message!</strong>');
17 
18$mailer->send($email);

Now we should be able to send this message. We can try it out by running it from the command line.

php index.php

And there you have it. You've just sent a mail using symfony/mailer.

Using a DSN

There is one more thing I'd like to show you, and that is creating a transporter based on a DSN. If you are unfamiliar with the term, DSN stands for Data Source Name. It is a string that represents the location of a data source. This data source can be anything like a file location, a database connection, or in our case a mail transport driver.

There is no real definitive format for a DSN, other than: it is a string. Symfony however has chosen to make their DSNs mirror a URI. So this format should be pretty familiar to you. If I were to say to you for example:

Create an url based on the ftp protocol, for the doeken.org domain, with username: john and password: doe on port 21.

You would probably give me a string like this: ftp://john:[email protected]:21.

In the case of a transporter DSN, the protocol is the name of the sender, so in our case: sendmail. So that would make our DSN sendmail:// This is however not a valid URI because there is no domain. To fix this, we can add a random string, but most prefer default. That means the final DSN is sendmail://default.

We can now use the Transport::fromDSN() method to automatically create the appropriate transport service.

2-use Symfony\Component\Mailer\Transport\SendmailTransport;
2+use Symfony\Component\Mailer\Transport;
3  
4 // ...
5  
7-$transport = new SendmailTransport();
7+$transport = Transport::fromDsn('sendmail://default');

$transport will now still hold a SendmailTransport instance, and the sending of the mail will still work.

If you wanted to send a mail using the smtp protocol you can provide a similar DSN. I like using HELO to debug my emails. A DSN for this could be: smtp://[email protected]:2500.

Testing

For testing purposes symfony/mailer includes a NullTransport service. This transporter will not send any mail, but it will trigger all the appropriate events. You can create this transporter using the null://default DSN.

Event Dispatching

As of version 5.4 the package can use any PSR-14 Event Dispatcher to emit events during the transport of an email.

To connect an Event Dispatcher to your Transporter, you can provide a second parameter to the ::fromDsn() method. The Transporter will then dispatch a MessageEvent containing the Email object, an Envelope and the Transporter itself. You can use this event to manipulate the Email instance before it is sent.

use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mailer\Exception\ExceptionInterface;
use Symfony\Component\Mime\Address;
 
$sender = Address::create('No-reply <[email protected]>');
 
$event_dispatcher = $this->getEventDispatcher(); // This should return your PSR-14 compliant dispatcher.
$event_dispatcher->subscribe(MessageEvent::class, function(MessageEvent $event) use ($sender): void {
// Updates any message to be sent from [email protected].
$event->getMessage()->setSender($sender);
});
 
$transport = Transport::fromDsn('sendmail://default', $event_dispatcher);

Do you want to learn more about event dispatching?
Then you should check out my in-depth post on Event Dispatching.

Documentation

If you want to learn more about the symfony/mailer package I highly recommend reading the docs. It goes into a lot of detail on the possible transport services, as well as using multiple transports at the same time, or even sending mails asynchronous by using a message queue.