How to use the Symfony mailer component to send emails?

by haylee.mertz , in category: PHP Frameworks , 14 days ago

How to use the Symfony mailer component to send emails?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 16 hours ago

@haylee.mertz 

To use the Symfony mailer component to send emails, you need to follow these steps:

  1. Install the Symfony mailer component using Composer:
1
composer require symfony/mailer


  1. Configure your email server settings in your Symfony application's .env file or .env.local file. Here's an example for using a Gmail account to send emails:
1
MAILER_DSN=gmail+smtp://<YOUR_GMAIL_ADDRESS>:<YOUR_GMAIL_PASSWORD>@smtp.gmail.com


  1. In your Symfony controller or service, import the SymfonyComponentMailerMailerInterface class and inject it as a dependency. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use SymfonyComponentMailerMailerInterface;

class MyController
{
    private $mailer;

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

    // ...
}


  1. Use the MailerInterface to create and send an email. Here's an example of creating and sending a basic email:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use SymfonyComponentMailerMailerInterface;
use SymfonyComponentMimeEmail;

class MyController
{
    private $mailer;

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

    public function sendEmail()
    {
        $email = (new Email())
            ->from('sender@example.com')
            ->to('recipient@example.com')
            ->subject('Hello!')
            ->text('This is a test email.');

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


You can also add attachments, HTML content, and more to your emails using the Email class. For more information, see the Symfony documentation on the mailer component: https://symfony.com/doc/current/mailer.html.