Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 styled emails best practices

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);
like image 895
Cybercarnage シ Avatar asked Jun 07 '14 09:06

Cybercarnage シ


2 Answers

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.

like image 73
Daria Sudakova Avatar answered Nov 06 '22 17:11

Daria Sudakova


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);
like image 31
Canser Yanbakan Avatar answered Nov 06 '22 17:11

Canser Yanbakan