Skip to content

How to send mail templated in Mailjet🔗

Sending email using template defined in mailjet allow our customers to manage mails design & content directly from mailjet.

Requirements🔗

  • symfony/mailer

Architecure🔗

Our component is made with at least 3 classes: - MailjetTransactionalMessageComposer: a class to generate an email with generics data - MailjetTemplateRegistry: allow to map our Mailer classes with Mailjet template ids - a Mailer: each mail is defined in his own class, this class should call the MailjetTransactionalMessageComposer class to generate a mail, then it must send it

Usage🔗

Create a mailer🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use Symfony\Component\Mailer\MailerInterface;

class ContactUsMailer
{
    private MailerInterface $mailer;
    private MailjetTransactionalMessageComposer $composer;
    private MailjetTemplateRegistry $templateRegistry;

    private string $recipient;

    public function __construct(
        MailerInterface $mailer,
        MailjetTransactionalMessageComposer $composer,
        MailjetTemplateRegistry $templateRegistry,
        string $recipient
    ) {
        $this->mailer = $mailer;
        $this->composer = $composer;
        $this->templateRegistry = $templateRegistry;
        $this->recipient = $recipient;
    }

    public function send(string $email, string $name, string $body): void
    {
        $mail = $this->composer->compose(
            md5($email.$name.$body.time()),
            $this->templateRegistry->get(self::class),
            '',
            $this->recipient,
            [
                'FROM' => $email,
                'NAME' => $name,
                'MSG' => $body,
            ]
        );

        $this->mailer->send($mail);
    }
}

Register it🔗

You will need to associate your mailer class with a mailjet template id by adding a new environment variable

1
2
#.env
MAILJET_TEMPLATE_CONTACT_US=123456789

And one entry in your TemplateRegistry:

1
2
3
4
5
6
# config/service.yaml

MailjetTemplateRegistry:
    arguments:
        -
            ContactUsMailer: '%env(int:MAILJET_TEMPLATE_CONTACT_US)%'

Common mistakes🔗

  • To use the mail subject defined in your mailjet template, you need to send an email with a blank subject from your application.

Project references🔗


Last update: December 20, 2024