New in Symfony 4.3: Mailer component
June 5, 2019 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
This means Swiftmailer is going to die?
Thank you for this great new addition to the Symfony ecosystem :)
I wonder if you have planned to release a library to retrieve emails from any inbox (gmail, ipage and so on).
Best regards.