Fabien Potencier
Contributed by Fabien Potencier in #30741

The stable version of Symfony 4.3 was released on May 30 2019, but there are still some new features we haven't talked about. In this article you'll learn about the Mailer component, the third component added by Symfony 4.3 (after Mime component and HttpClient component).

The Mime component allows you to create email messages, but to actually send them, you need to use the Mailer component. Emails are delivered via a "transport", which can be a local SMTP server or a third-party mailing service.

Out of the box this component provides support for the most popular services: Amazon SES, MailChimp, Mailgun, Gmail, Postmark and SendGrid. They are installed separately, so if your app uses for example Amazon SES, run this command:

1
$ composer require symfony/amazon-mailer

This will add some environment variables in your .env file where you can configure the specific service you are using:

1
2
3
4
# .env
AWS_ACCESS_KEY=...
AWS_SECRET_KEY=...
MAILER_DSN=smtp://$AWS_ACCESS_KEY:$AWS_SECRET_KEY@ses

That's all. You can now inject the mailer service in any service or controller by type-hinting a constructor argument with the MailerInterface class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

class SomeService
{
    private $mailer;

    public function __construct(MailerInterface $mailer)
    {
        $this->mailer = $mailer;
    }

    public function sendNotification()
    {
        $email = (new Email())
            ->from('hello@example.com')
            ->to('you@example.com')
            ->subject('Time for Symfony Mailer!')
            ->text('Sending emails is fun again!')
            ->html('<p>See Twig integration for better HTML integration!</p>');

        $this->mailer->send($email);
    }
}

When you call $this->mailer->send($email), the email message is sent to the transport immediately. To improve performance, you can leverage the Messenger component to send the messages later via a Messenger transport. Read the Sending Messages Async section in the Mailer docs to learn more about this.

Published in #Living on the edge