Symfony2 styled emails best practices
Asked Answered
F

2

6

What are the best practices to send emails from html & css? I have much mails in my projects & need the solution, that can allow me not to write all below code again & again:

$msg = \Swift_Message::newInstance()
    ->setSubject('Test')
    ->setFrom('[email protected]')
    ->setTo('[email protected]')
    ->setBody($this->renderView('MyBundle:Default:email1.text.twig'));

$this->get('mailer')->send($msg);
Flattish answered 7/6, 2014 at 9:0 Comment(0)
I
7

Maybe my answer can help. There is a special bundle Symfony2-MailerBundle that render email body from template and allows to set up sending parameters in config file & you won't have to pass them every time you want to build & send email.

Intimate answered 7/6, 2014 at 9:8 Comment(0)
S
4

Set that code as a function in a service. Functions are for that.

To create a service see the link below.

How to inject $_SERVER variable into a Service

Note: don't forget to inject the mail service as an argument!

arguments: ["@mailer"]

After you set your service;

public function sendMail($data)
{
    $msg = \Swift_Message::newInstance()
        ->setSubject($data['subject'])
        ->setFrom($data['from'])
        ->setTo($data['to'])
        ->setBody($this->renderView($data['view']));

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

And you can call your service like;

// this code below is just for setting the data
$data = [
    'subject' => 'Hello World!', 
    'from' => '[email protected]', 
    'to' => '[email protected]', 
    'template' => 'blabla.html.twig'
];

// this code below is the actual code that will save you
$mailer = $this->get('my_mailer_service');
$mailer->sendMail($data);
Slough answered 7/6, 2014 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.