How to use symfony/mailer without the Symfony framework

Posted on

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
Enter fullscreen mode

Exit fullscreen mode

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

{
    "name": "symfony-mailer-test",
    "require": {}
}
Enter fullscreen mode

Exit fullscreen mode

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

composer require symfony/mailer
Enter fullscreen mode

Exit fullscreen mode

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

require_once 'vendor/autoload.php';
Enter fullscreen mode

Exit fullscreen mode

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

use SymfonyComponentMimeEmail;

$email = (new Email())
    ->from('sender@example.test')
    ->to('your-email@here.test')
    ->priority(Email::PRIORITY_HIGHEST)
    ->subject('My first mail using Symfony Mailer')
    ->text('This is an important message!')
    ->html('<strong>This is an important message!</strong>');
Enter fullscreen mode

Exit fullscreen mode

As you can see, 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.

use SymfonyComponentMailerMailer;
use SymfonyComponentMailerTransportSendmailTransport;

$transport = new SendmailTransport();
$mailer = new Mailer($transport);

$mailer->send($email);
Enter fullscreen mode

Exit fullscreen mode

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

php index.php
Enter fullscreen mode

Exit fullscreen mode

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 a 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:doe@doeken.org: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.

use SymfonyComponentMailerTransportTransport;

$transport = Transport::fromDsn('sendmail://default');
Enter fullscreen mode

Exit fullscreen mode

$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://symfony-mailer@127.0.0.1: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.



Events

I won’t be covering events in this blog post, but this is something that symfony/mailer supports. As of version 5.3 the only event dispatcher package you can use is symfony/event-dispatcher. When 5.4 is released, and Swiftmailer will officially be retired, you can use any PSR-14 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.

I hope you enjoyed reading this article! If so, please leave a ❤️ or a and consider subscribing! I write posts on PHP most every week.

Leave a Reply

Your email address will not be published. Required fields are marked *