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.com
and 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 variablename
toJohn Doe
$mailer->send($email);
: sends the email
Helpful links
More of Php Symfony
- How to create a model in PHP Symfony?
- How to install Symfony on Windows?
- How to create a migration in PHP Symfony?
- How to check PHP Symfony version?
- How to use PHP Symfony with gRPC?
- How to integrate Vue.js with PHP Symfony?
- How to install PHP Symfony on Ubuntu?
- How to do testing with PHP Symfony?
- How to update PHP Symfony?
- How to use the PHP Symfony factory?
See more codes...