Search code examples
phpsymfonyemailswiftmailer

SwiftMailer can not send TemplatedEmail , symfony 4


here is what swiftmailer says, despite the symfony 4 docs saying we cound send such TemplatedEmail object, it is not possible:

Argument 1 passed to Swift_Mailer::send() must be an instance of Swift_Mime_SimpleMessage, instance of Symfony\Bridge\Twig\Mime\TemplatedEmail given, called in /home/tk/html/src/Service/MailService.php on line 103

code to send my html mail inside my MailService:

// ...
use Swift_Mailer;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;

class MailService {

// ...

public function sendOwnerPollsAction( Owner $foundOwner ) {

        // anti spam , limit to every minute TODO
//      $lastSend = $admin_user->getRequestedPollsDate();
//      $now      = new \DateTime();

//      if ( date_diff( $lastSend, $now ) < 60 ) {
//          // too soon!
//          die( 'too soon!' );
//      }
//      $admin_user->setRequestedPollsDate( $now );
//      $em->persist( $admin_user );
//      $em->flush();
        $titleEmail = 'Framadate | Mes sondages';

        $templateVars = [
            'owner'          => $foundOwner,
            'title'          => $titleEmail,
            'email_template' => 'emails/owner-list.html.twig',
        ];

        $email = ( new TemplatedEmail() )
            ->from( 'ne-pas-repondre@framadate-api.cipherbliss.com' )
            ->to( new Address( $foundOwner->getEmail() ) )
            ->subject( $titleEmail )
            ->htmlTemplate( $templateVars[ 'email_template' ] )
            ->context( $templateVars );

        // send email
        return $this->mailer->send( $email );
    }

the swiftmailer doc for symfony 4 says we can send mails like that, and that templatedemail extend Email. https://symfony.com/doc/4.3/mailer.html#creating-sending-messages so i don't get how we could send templated html emails.

packages:

"symfony/framework-bundle": "4.3.*",
"symfony/swiftmailer-bundle": "^3.4",
"php": "^7.1.3",

Solution

  • You're mixing Symfony Mailer with Swift Mailer.

    TemplatedEmail is from SymfonyMailer, but you are trying to send with SwiftMailer. Therefore the error.

    If you truly want to use Swift Mailer then require your TemplateEmail Section.

    Auszug von SwiftMailer for Symfony :

    $message = (new \Swift_Message($titleEmail))
            ->setFrom('ne-pas-repondre@framadate-api.cipherbliss.com')
            ->setTo(new Address( $foundOwner->getEmail() ))
            ->setBody(
                $this->renderView(
                    'emails/owner-list.html.twig',
                    [
                    'title'          => $titleEmail,
                    'email_template' => 'emails/owner-list.html.twig'
                    ]
                ),
                'text/html'
            )
    
    $mailer->send($message);
    

    If you want to use TemplatedEmail with SymfonyMailer, then follow Mailer on Symfony. There is additional config to be done.