How to define an additional mailer service to use the spool and send instant emails in Symfony2
Asked Answered
T

1

7

In my Symfony2 web app I'm supposed to send two kind of emails: instant and bulk. The instant emails should be send right away while the bulk emails should be send using the spool. With the default configuration of the Swiftmailer in Symfony2 it is impossible to do that because there is only one mailer service.

Similar questions has been asked here in SO ( How to spool emails (in a task) and send normal emails in the moment in the other controllers? ) with no luck, but according to this github thread ( https://github.com/symfony/SwiftmailerBundle/issues/6 ) it is possible to create a second mailer service that can be configured totally different than the default one. Someone there (stof) recommended as a possible solution to follow the configuration found in the SwiftmailerBundle ( https://github.com/symfony/SwiftmailerBundle/blob/master/Resources/config/swiftmailer.xml ) to create this new service, but I don't know how exactly do that.

Does anyone know how to create an additional mailer service that I can configured as a spool while having the default mailer service to send regular (instant) emails?

Textuary answered 4/9, 2012 at 19:33 Comment(0)
T
12

I found the solution here

This is how I implemented it:

First, I configured the default mailer service to work as a spool to send bulk emails.

(config.yml)

swiftmailer:
    transport: %mailer_transport%
    encryption: %mailer_encryption%
    auth_mode: %mailer_auth_mode%
    host: %mailer_host%
    username: %mailer_user%
    password: %mailer_password%
    spool:
        type: file
        path: "%kernel.root_dir%/spool"

Then, inside one of my bundles (CommonBundle) I registered a new service called "instant_mailer" that maps to the Swiftmailer class.

(service.yml)

instant_mailer:
    class: %swiftmailer.class%
    arguments: ["@?swiftmailer.transport.real"]

Finally, in my controller, whenever I want to send an email usning the spool I just do:

$mailer = $this->get('mailer');

And to send an instant email:

$mailer = $this->get('instant_mailer');
Textuary answered 4/9, 2012 at 20:13 Comment(1)
Nice! But you may run into issues if one environment uses spooling and the other doesn't. You might want to check if $this->get('mailer')->getTransport() instanceof \Swift_Transport_SpoolTransport before switching to the .real transport since it may not exist!Sandisandidge

© 2022 - 2024 — McMap. All rights reserved.