How to send email in Symfony?

by scotty_walker , in category: PHP Frameworks , 8 months ago

How to send email in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 3 months ago

@scotty_walker 

To send an email in Symfony, you can use the built-in SwiftMailer bundle. Here is an example of how to send an email:

  1. First, make sure you have the SwiftMailer bundle installed and configured in your Symfony project.
  2. In your controller or service, inject the Swift_Mailer service:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use SymfonyComponentMailerMailerInterface;

class MyController
{
    private $mailer;

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


  1. Then, use the createMessage() method of the $mailer object to create a new email message:
1
2
3
4
5
$message = (new Swift_Message('Hello Email'))
    ->setFrom('sender@example.com')
    ->setTo('recipient@example.com')
    ->setBody('This is the message body')
;


  1. Finally, use the send() method to send the email:
1
$this->mailer->send($message);


You can also customize the email further by setting the subject, adding attachments, etc. For more information, you can check out the SwiftMailer documentation:


https://symfony.com/doc/current/mailer.html