Swiftmailer//Twig email not rendering correctly

Cláudio Ribeiro picture Cláudio Ribeiro · Sep 11, 2012 · Viewed 8.2k times · Source

I'm experimenting with symfony2 framework and i'm trying to send emails using swiftmailer and twig. The problem is, with my current implementation, the email is sent in html (you can see the tags, everything).

Here is the controller i'm using:

 public function formularioAction()
{   
    $enquiry = new Enquiry();
    $form = $this->createForm(new EnquiryType(), $enquiry);

    $request = $this->getRequest();
    if($request->getMethod() == 'POST'){
        $form->bindRequest($request);

        if($form->isValid()){

            $message = \Swift_Message::newInstance()
                    ->setSubject('Mail from the App')
                    ->setFrom('[email protected]')
                    ->setTo('******@gmail.com')
                    ->setBody($this->render( 'AcmeDemoBundle:Demo:email.html.twig' ));

            $this->get('mailer')->send($message);
            //end of mail sending

            //redirect - it's important to prevent users from reposting the form if
            //they refresh the page
            return $this->redirect($this->generateUrl( '_formulario'));
        }
    }
    return $this->render('AcmeDemoBundle:Demo:formulario.html.twig', array('form' => $form->createView()));
}

And the twig template the email is using:

{% extends "AcmeDemoBundle::layout.html.twig" %}

{% block title "Email de teste" %}

{% block content%}
<H1>Este é um render de um email de teste!</H1>
{% endblock%}

What am i doing wrong?

Answer

Ajb picture Ajb · Sep 11, 2012

You have to specify the Content-type of the body, by calling the setBody() method like this.

$message->setBody($messageBody, 'text/html');

For more information, see: http://swiftmailer.org/docs/messages.html#setting-the-body-content