php-symfonyHow to use the PHP Symfony mailer?
The PHP Symfony mailer is a library that allows you to send emails from your Symfony application. It is easy to use and provides a lot of flexibility.
Example code
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
$transport = new EsmtpTransport('smtp.example.com', 25);
$mailer = new Mailer($transport);
$email = (new TemplatedEmail())
->from('[email protected]')
->to('[email protected]')
->subject('Hello!')
->htmlTemplate('emails/hello.html.twig')
->context(['name' => 'John Doe']);
$mailer->send($email);
This example code will send an email from [email protected] to [email protected] with the subject Hello! and the HTML template emails/hello.html.twig with the context variable name set to John Doe.
Code explanation
use Symfony\Component\Mailer\Mailer;: imports the Mailer class from the Symfony Mailer libraryuse Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;: imports the EsmtpTransport class from the Symfony Mailer library$transport = new EsmtpTransport('smtp.example.com', 25);: creates a new EsmtpTransport object with the SMTP serversmtp.example.comand port25$mailer = new Mailer($transport);: creates a new Mailer object with the EsmtpTransport object$email = (new TemplatedEmail()): creates a new TemplatedEmail object->from('[email protected]'): sets the sender of the email to[email protected]->to('[email protected]'): sets the recipient of the email to[email protected]->subject('Hello!'): sets the subject of the email toHello!->htmlTemplate('emails/hello.html.twig'): sets the HTML template of the email toemails/hello.html.twig->context(['name' => 'John Doe']): sets the context variablenametoJohn Doe$mailer->send($email);: sends the email
Helpful links
More of Php Symfony
- How to install Symfony on Windows?
- How to get request parameters in PHP Symfony?
- How to use Prometheus with PHP Symfony?
- How to upload a file in PHP Symfony?
- How to create a model in PHP Symfony?
- How to use the messenger component in PHP Symfony?
- How to process async tasks in PHP Symfony?
- How to use OpenAPI with PHP Symfony?
- How to connect to MySQL in PHP Symfony?
- How to use the PHP Symfony factory?
See more codes...