Symfony SwiftMailer:如果控制器没有 return $this->render() 响应则不发送

Symfony SwiftMailer: not sending if the controller does not return a $this->render() response

我有一个 Symfony 项目(非常简化)如下所示:

Controller/MyToolController.php

namespace App\Controller;

use App\Services\ToolsService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyToolController extends AbstractController
{
    private $toolsService;


    /**
     * @param ToolsService|null $toolsService
     */
    public function __construct(ToolsService $toolsService = null) {
        $this->toolsService = $toolsService;
    }

    public function run() {
        // some more code here...

        $mailContent = $this->render('site/mail.html.twig', $data)->getContent();
        $this->toolsService->sendMail($from, $to, $bcc, $mailContent, $subject);

        // if I remove the following line, no emails are sent out!
        return $this->render('site/thankyou.html.twig', $data);

    }
}

Services/MyToolService.php

namespace App\Services;

class ToolsService
{

    /** @var \Swift_Mailer */
    private $mailer;

    /**
     * @param \Swift_Mailer $mailer
     */
    public function __construct(\Swift_Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function sendMail($from, $to, $bcc, $body, $subject) {
        $mail = ( new \Swift_Message() )
            ->setSubject($subject)
            ->setFrom($from)
            ->setTo($to)
            ->setBcc($bcc)
            ->addPart($body, 'text/html');

        $res = $this->mailer->send($mail);
        $this->logger->info('Email sent');

        return $res;
    }
}

如果您查看 MyToolController.php,您会看到我调用了一个发送电子邮件的服务。

如果我在我的 run() 函数中 return 一个 Response 对象,一切都会顺利 - 但如果我忽略它,则不会发送任何内容。如果我在一个循环中发送多封电子邮件并且我 运行 超时也是如此。

奇怪的是 $mailer->send() 在任何情况下都会被调用 - 它 returns 1 - 我在 sendmail() 函数中写的日志中看到一个条目。但是没有电子邮件离开服务器。

这是我的 SwiftMailer 配置:

swiftmailer:
    url: '%env(MAILER_URL)%'
    spool: { type: 'memory' }

您的邮件正在内存中假脱机,which means

When you use spooling to store the emails to memory, they will get sent right before the kernel terminates. This means the email only gets sent if the whole request got executed without any unhandled exception or any errors.

如果您不 return 来自控制器的 Response 对象, 成为未处理的异常,整个请求 不会执行,永远不会发送邮件

控制器需要return一个Symfony\Component\HttpFoundation\Response才能正常处理请求。如果你想 return 一个空的响应,你可以简单地做:

return new Response();