Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silex + Swift Mailer not working

I have a Silex app with Swift Mailer, but it seems like the configuration was not loaded from $app['swiftmailer.options'].

I registered the service in my bootstrap file

$app->register(new SwiftmailerServiceProvider());

And in my configuration file

$app['swiftmailer.options'] = array(
    'host' => 'smtp.mandrillapp.com',
    'port' => '587',
    'username' => 'MY_USERNAME',
    'password' => 'MY_PASSWORD',
    'encryption' => null,
    'auth_mode' => null
);

And then I send my email with

$message = \Swift_Message::newInstance()
    ->setSubject($this->app['forum_name'] . ' Account Verification')
    ->setFrom(array('[email protected]'))
    ->setTo(array('[email protected]'))
    ->setBody('My email content')
    ->setContentType("text/html");

$this->app['mailer']->send($message);

The send function returns 1 but the email was never sent. But, when I try manually creating an instance of Swift_SmtpTransport, the email would send.

$transport = \Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587)
    ->setUsername('MY_USERNAME')
    ->setPassword('MY_PASSWORD');
...
$mailer = \Swift_Mailer::newInstance($transport);
$mailer->send($message);

So the problem is the $app['swiftmailer.options'] is not read or loaded. Am I missing something here?

I'm following the instructions from here.

like image 998
Raphael Marco Avatar asked Oct 20 '22 16:10

Raphael Marco


2 Answers

By default the SwiftmailerServiceProvider uses a spooled transport to queue up emails and sends them all during the TERMINATE stage (after a response is sent back to the client). If you don't call Application->run(), you are bypassing this process. Your mail will stay in the spool and never get sent.

If you want to sent mail outside of the normal Silex flow, you can flush the spool manually with

if ($app['mailer.initialized']) {
    $app['swiftmailer.spooltransport']
        ->getSpool()
        ->flushQueue($app['swiftmailer.transport']);
}

That's taken directly from the SwiftmailerServiceProvider.

Or you can simply turn off spooling with

$app['swiftmailer.use_spool'] = false;
like image 130
Justin Howard Avatar answered Oct 22 '22 17:10

Justin Howard


Try this:

$app->register(new \Silex\Provider\SwiftmailerServiceProvider(), array(
   'swiftmailer.options' => array(
        'sender' => 'sender',
        'host' => 'host',
        'port' => 'port',
        'username' => 'username',
        'password' => 'password'
   )
));

It is not in the documentation.

like image 40
Todor.Angelov Avatar answered Oct 22 '22 19:10

Todor.Angelov