I am making a console application which uses the SwiftMail extension to send. Due to our policy, I have two virtual machines, one which serves as a SMTP relay and the other whic
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!