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

Gerfried :

I have a Symfony project which (very simplified) looks like this:

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

If you look at MyToolController.php you see that I call a service which sends the email.

If I return a Response object in my run() function, everything goes well - but if I omit this, nothing is sent. Same if I send multiple emails in a loop and I run into a timeout.

Strangely $mailer->send() is called in any case - and it returns 1 - and I see an entry in the log I am writing in the sendmail() function. But no email leaves the server.

This is my SwiftMailer configuration:

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

Your mails are being spooled in 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.

If you do not return a Response object from your controller, there will be an unhandled exception, the whole request won't be executed, and the mails will never be sent.

Controllers need to return a Symfony\Component\HttpFoundation\Response so the request can be handled normally. If you want to return an empty response, you can simply do:

return new Response();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=24325&siteId=1