How to use symfony/mailer without the Symfony framework
Tags: webdev, programming, php, tutorial
Published: 2021-09-11 10:07:14

On August 19, 2021, Fabien Potencier officially announced [the end of maintenance for Swiftmailer](https://symfony.com/blog/the-end-of-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](https://symfony.com/doc/current/mailer.html#using-a-3rd-party-transport).

### 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](https://en.wikipedia.org/wiki/MIME). 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](https://www.php.net/manual/en/class.serializable.php).

## 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:

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

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

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

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

```bash
composer require symfony/mailer
```

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

```php
require_once 'vendor/autoload.php';
```

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

```php
use Symfony\Component\Mime\Email;

$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>');
```

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.

```php
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport\SendmailTransport;

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

$mailer->send($email);
```

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

```bash
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](https://en.wikipedia.org/wiki/Data_source_name). 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.

```php
use Symfony\Component\Mailer\Transport\Transport;

$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](https://usehelo.com/) 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](https://www.php-fig.org/psr/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](https://doeken.org/blog/event-dispatching-exploration).

## Documentation
If you want to learn more about the `symfony/mailer` package I highly recommend [reading the docs](https://symfony.com/doc/current/mailer.html). 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.*