Silex SwiftMailer Not Making SMTP Connection Upon Execution

北慕城南 提交于 2019-12-02 17:44:55
igorw

This is because the SwiftmailerServiceProvider uses a Swift_MemorySpool by default, and only flushes that on kernel.terminate. Let me take a step back and explain each part of this.

  • The SwiftmailerServiceProvider is responsible for registering the Swiftmailer services and default configuration. By default the transport (swiftmailer.spooltransport) is Swift_SpoolTransport and the swiftmailer.spool is Swift_MemorySpool.

  • Swiftmailer supports different ways of sending the mails. These are called transports. The spool transport acts as a queue. You can either store this queue in a file or in memory. Spool transports have a flushQueue method which allows flushing the queued mails to a real transport, which should deliver them.

  • The Symfony2 HttpKernel which Silex uses emits a number of events during the lifecycle of every request. The last one that it emits is the kernel.terminate event. This event is triggered after the HTTP response body has been sent. This allows you to do heavy tasks after rendering the page, so that it no longer appears as loading to the user.

  • The SwiftmailerServiceProvider subscribes to the kernel.terminate event in order to flush the memory spool after the page has been rendered. It flushes it to swiftmailer.transport service, which is a Swift_Transport_EsmtpTransport that does the actual sending via SMTP.

So let's get to the actual problem. You are in a CLI context, so none of those HttpKernel events will be fired. And since the kernel.terminate event is not fired, your spool is not being flushed. And thus your emails are not getting sent.

There's two good solutions for this:

  • A) Flush the spool manually. Just do what the provider does in its listener. Add this at the end of your CLI command:

    if ($app['mailer.initialized']) {
        $app['swiftmailer.spooltransport']->getSpool()->flushQueue($app['swiftmailer.transport']);
    }
    
  • B) Re-configure the mailer service to use the ESMTP transport directly without going through the spool:

    $app['mailer'] = $app->share(function ($app) {
        return new \Swift_Mailer($app['swiftmailer.transport']);
    });
    

Either solution should do. Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!