Question

Looking in the documentation swiftmailer, in order to include both the message format to text in HTML format you need to use the method addPart: swiftmailer doc

// Give it a body
->setBody('Here is the message itself')

// And optionally an alternative body
->addPart('<q>Here is the message itself</q>', 'text/html')

But to my surprise this method is not found by Symfony2 and I do not know how to solve my problem.

Any idea?

Was it helpful?

Solution 2

This is what I use and for me this is works:

$message = \Swift_Message::newInstance()
                ->setSubject($subject)
                ->setFrom($from)
                ->setTo($emailAddress)
                ->setBody(
                    $this->templating->render(
                        $template.'.txt.twig',
                        $parameterArray
                    )
                )
                ->addPart(
                    $this->templating->render(
                        $template.'.html.twig',
                        $parameterArray
                    ),'text/html'
                );

OTHER TIPS

If you are receiving this Method 'addpart' not found in \Swift_Mime_MimePart message in an IDE, in my case PHP Storm, then I found that I had to re-declare the $message variable as a \Swift_Message object.

The IDE is using the return value type of the parent class Swift_Mime_MimePart as it is using a parent method, and so it does not accept a child method in the child class Swift_Message.

Not very tidy, as it breaks the method chaining, but it does resolve the analysis errors:

$message = \Swift_Message::newInstance()
    ->setSubject('Hello Email')
    ->setFrom('send@example.com')
    ->setTo('recipient@example.com')
    ->setBody(
        $this->renderView(
            // app/Resources/views/Emails/registration.html.twig
            'Emails/registration.html.twig',
            array('name' => $name)
        ),
        'text/html'
    )
;
/* @var \Swift_Message $message */
$message
    ->addPart(
        $this->renderView(
            'Emails/registration.txt.twig',
            array('name' => $name)
        ),
        'text/plain'
    )
;
$this->get('mailer')->send($message);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top