The SwiftmailerServiceProvider provides a service for sending email through the Swift Mailer library.
You can use the mailer
service to send messages easily. By default, it
will attempt to send emails through SMTP.
swiftmailer.use_spool: A boolean to specify whether or not to use the memory spool, defaults to true.
swiftmailer.options: An array of options for the default SMTP-based configuration.
The following options can be set:
Example usage:
1 2 3 4 5 6 7 8 | $app['swiftmailer.options'] = array(
'host' => 'host',
'port' => '25',
'username' => 'username',
'password' => 'password',
'encryption' => null,
'auth_mode' => null
);
|
mailer: The mailer instance.
Example usage:
1 2 3 4 5 | $message = \Swift_Message::newInstance();
// ...
$app['mailer']->send($message);
|
swiftmailer.transport: The transport used for e-mail
delivery. Defaults to a Swift_Transport_EsmtpTransport
.
swiftmailer.transport.buffer: StreamBuffer used by the transport.
swiftmailer.transport.authhandler: Authentication handler used by the transport. Will try the following by default: CRAM-MD5, login, plaintext.
swiftmailer.transport.eventdispatcher: Internal event dispatcher used by Swiftmailer.
1 | $app->register(new Silex\Provider\SwiftmailerServiceProvider());
|
Note
SwiftMailer comes with the "fat" Silex archive but not with the regular one. If you are using Composer, add it as a dependency:
1 | composer require swiftmailer/swiftmailer
|
The Swiftmailer provider provides a mailer
service:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $app->post('/feedback', function () use ($app) {
$request = $app['request'];
$message = \Swift_Message::newInstance()
->setSubject('[YourSite] Feedback')
->setFrom(array('noreply@yoursite.com'))
->setTo(array('feedback@yoursite.com'))
->setBody($request->get('message'));
$app['mailer']->send($message);
return new Response('Thank you for your feedback!', 201);
});
|
By default, the Swiftmailer provider sends the emails using the KernelEvents::TERMINATE
event, which is fired after the response has been sent. However, as this event
isn't fired for console commands, your emails won't be sent.
For that reason, if you send emails using a command console, it is recommended
that you disable the use of the memory spool (before accessing $app['mailer']
):
$app['swiftmailer.use_spool'] = false;
Alternatively, you can just make sure to flush the message spool by hand before ending the command execution. To do so, use the following code:
$app['swiftmailer.spooltransport']
->getSpool()
->flushQueue($app['swiftmailer.transport'])
;
Silex\Application\SwiftmailerTrait
adds the following shortcuts:
1 2 3 4 5 | $app->mail(\Swift_Message::newInstance()
->setSubject('[YourSite] Feedback')
->setFrom(array('noreply@yoursite.com'))
->setTo(array('feedback@yoursite.com'))
->setBody($request->get('message')));
|
For more information, check out the Swift Mailer documentation.