【问题标题】:SwiftMailer can not send TemplatedEmail , symfony 4SwiftMailer 无法发送 TemplatedEmail , symfony 4
【发布时间】:2020-04-14 17:06:59
【问题描述】:

这是 swiftmailer 所说的,尽管 symfony 4 文档说我们可以发送这样的 TemplatedEmail 对象,但这是不可能的:

传递给 Swift_Mailer::send() 的参数 1 必须是 Swift_Mime_SimpleMessage,实例 Symfony\Bridge\Twig\Mime\TemplatedEmail 给定,调用 /home/tk/html/src/Service/MailService.php 在第 103 行

在我的 MailService 中发送我的 html 邮件的代码:

// ...
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 );
    }

symfony 4 的 swiftmailer 文档说我们可以发送这样的邮件,并且 templatedemail 扩展了电子邮件。 https://symfony.com/doc/4.3/mailer.html#creating-sending-messages 所以我不明白我们如何发送模板化的 html 电子邮件。

包:

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

【问题讨论】:

  • Symfony Mailer,在 4.3 中引入,与 Swift Mailer 不同。如果您想继续使用 Swift,您可以将 twig Environment 注入您的服务并手动渲染模板。

标签: php symfony email swiftmailer


【解决方案1】:

您正在将 Symfony Mailer 与 Swift Mailer 混合使用。

TemplatedEmail 来自 SymfonyMailer,但您尝试使用 SwiftMailer 发送。因此错误。

如果你真的想使用 Swift Mailer,那么需要你的 TemplateEmail 部分。

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);

如果您想将 TemplatedEmail 与 SymfonyMailer 一起使用,请关注 Mailer on Symfony。还有一些额外的配置要做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2019-04-09
    • 2019-10-05
    相关资源
    最近更新 更多