Swiftmailer en una aplicaciĆ³n Symfony4

Jun. 2018 (es) Symfony 4 Swiftmailer

Albert Serra

1. InstalaciĆ³n

2. ConfiguraciĆ³n

// config/packages/swiftmailer.yaml
swiftmailer:
    url: 'smtp://hosting.com:25?auth_mode=login&username=username@hosting.com&password=MYPASSWORD'
    spool: { type: 'memory' }

3. Controller

    // src/Controller/DefaultController.php

     /**
     * @Route("/email/test", name="email_test")
     */

    public function emailTest( Request $request, \Swift_Mailer $mailer )
    {

        $objs = $this->getDoctrine()->getRepository(User::class)->findBy([]);
        $obj = $objs[0];

        $message = (new \Swift_Message('Proyecto - Bienvenido'))
            ->setFrom( array('usuario@dominio.com' => 'Web' ) )
            ->setTo( array('info@albertserra.cat' => 'Albert Serra') )
            ->setBody(
                $this->renderView(
                    // templates/emails/registration.html.twig
                    'emails/usuario.html.twig',
                    array('obj' => $obj )
                ),
                'text/html'
            );

            $mailer->send($message);

        return new Response('true');
    }

4. Configurar Template

<html lang="es">
 <head>
     <meta charset="utf-8">
 </head>
 <body style="font-family: 'Open Sans', Helvetica, Arial, sans-serif; background-color: white;">

    <div style="text-align: center; margin: 20px auto;">
        <img class="logo" src="{{ absolute_url( asset('build/images/og-image.jpg') ) }}" alt="" style="width: 250px;">
    </div>

    <div style="width: 400px; margin: auto; box-sizing: border-box; font-size: 14px;">

    <p>Hola {{ obj.name }},</p>
    <p>Gracias por registrate.</p>
    <p>Validar correo: {{ url('path_name') }}</p>
    </div>

 </body>
 </html>

EOF