Symfony - Mailer

tags: Symfony gobelins

Plusieurs façon d'envoyer un mail :

  • Utilisation de Swift Mailer > version antérieur (créer en 2009)
  • Utilisation de Mailer > 2019

Notre choix : Mailer

  • Codebase moderne
  • Structure de classe + simple
  • Meilleur intégration de Twig
  • Intégration pièces jointes et images

Etapes principales

Installation

composer require symfony/mailer

Configuration

Différents protocoles :

  • SMTP
  • HTTP
  • API

Pour configurer il faut changer le DSN du fichier .env :

MAILER_DSN=gmail+smtp://USERNAME:PASSWORD@default

Le password correspond au mot de passe de l'application

Création & envoi de l'email

Il faut créer un Maileur Contrôleur

// src/Controller/MailerController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

class MailerController extends AbstractController
{
    /**
     * @Route("/email")
     */
    public function sendEmail(MailerInterface $mailer)
    {
        $email = (new Email())
            ->from('hello@example.com')
            ->to('you@example.com')
            //->cc('cc@example.com')
            //->bcc('bcc@example.com')
            //->replyTo('fabien@example.com')
            //->priority(Email::PRIORITY_HIGH)
            ->subject('Time for Symfony Mailer!')
            ->text('Sending emails is fun again!')
            ->html('<p>See Twig integration for better HTML integration!</p>');

        $mailer->send($email);

        // ...
    }
}

Pour aller plus loin

Ajout d'un header au mail


$email = (new Email())
    ->getHeaders()
        // this header tells auto-repliers ("email holiday mode") to not
        // reply to this message because it's an automated email
        ->addTextHeader('X-Auto-Response-Suppress', 'OOF, DR, RN, NRN, AutoReply');

    // ...
;

Ajout de pièces jointes

$email = (new Email())
    // ...
    ->attachFromPath('/path/to/documents/terms-of-use.pdf')
    // optionally you can tell email clients to display a custom name for the file
    ->attachFromPath('/path/to/documents/privacy.pdf', 'Privacy Policy')
    // optionally you can provide an explicit MIME type (otherwise it's guessed)
    ->attachFromPath('/path/to/documents/contract.doc', 'Contract', 'application/msword')
;

Ajout d'images

$email = (new Email())
    // ...
    // get the image contents from a PHP resource
    ->embed(fopen('/path/to/images/logo.png', 'r'), 'logo')
    // get the image contents from an existing file
    ->embedFromPath('/path/to/images/signature.gif', 'footer-signature')
;

Gestion des erreurs

use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

$email = new Email();
// ...
try {
    $mailer->send($email);
} catch (TransportExceptionInterface $e) {
    // some error prevented the email sending; display an
    // error message or try to resend the message
}

Gestion du style / templating


// path of the Twig template to render
->htmlTemplate('emails/signup.html.twig')

le template :

{# templates/emails/signup.html.twig #}
<h1>Welcome {{ email.toName }}!</h1>

<p>
    You signed up as {{ username }} the following email:
</p>
<p><code>{{ email.to[0].address }}</code></p>

<p>
    <a href="#">Click here to activate your account</a>
    (this link is valid until {{ expiration_date|date('F jS') }})
</p>