php-swiftmailerHow to use Swiftmailer with Symfony?
Swiftmailer is a popular library for sending emails in Symfony applications. It is easy to use and provides a lot of features.
To use Swiftmailer with Symfony, first install the library using Composer:
composer require swiftmailer/swiftmailer
Then, configure the Swiftmailer settings in the config/packages/swiftmailer.yaml
file:
swiftmailer:
transport: '%env(MAILER_URL)%'
username: '%env(MAILER_USERNAME)%'
password: '%env(MAILER_PASSWORD)%'
Finally, create a service to send emails using Swiftmailer:
<?php
namespace App\Service;
use Swift_Mailer;
class Mailer
{
private $mailer;
public function __construct(Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function sendEmail($subject, $from, $to, $body)
{
$message = (new \Swift_Message($subject))
->setFrom($from)
->setTo($to)
->setBody($body);
$this->mailer->send($message);
}
}
Code explanation
composer require swiftmailer/swiftmailer
: Installs the Swiftmailer library.swiftmailer:
: Configures the Swiftmailer settings in theconfig/packages/swiftmailer.yaml
file.public function __construct(Swift_Mailer $mailer)
: Creates a service to send emails using Swiftmailer.$message = (new \Swift_Message($subject))
: Creates a new Swift_Message instance.$this->mailer->send($message)
: Sends the email.
Helpful links
More of Php Swiftmailer
- How to set timeout with Swiftmailer?
- How to use SMTP with Swiftmailer?
- How to use TLS 1.2 with Swiftmailer?
- How to get the response code when using Swiftmailer?
- How to use Swiftmailer to send RFC 2822 compliant emails?
- How to configure Swiftmailer for Postfix?
- How to send emails in UTF8 using Swiftmailer?
- How to send emails to multiple recipients with Swiftmailer?
- How to set the port for Swiftmailer?
- How to enable TLS with Swiftmailer?
See more codes...