Multiple instances of Swiftmailer in Symfony2
Asked Answered
L

2

6

Symfony2 uses a Swiftmailer bundle to send emails.

To use and configure Swiftmailer in Symfony2, one has to use such a configuration as explained in the docs, e.g. by using YAML:

swiftmailer:
    transport:  smtp
    encryption: ssl
    auth_mode:  login
    host:       smtp.gmail.com
    username:   your_username
    password:   your_password

The Swiftmailer is defined in Symfony2 as a service and an instance of it can be obtained in a controller as follows:

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

Now, let's suppose that two different configurations are required for the Swiftmailer, e.g. one that uses email spooling (e.g. for a scheduled newsletter) and another that sends immediately all the new emails (e.g. for the password lost service). Thus, I guess that two separated instances of the Swiftmailer should be defined. How can I do that in Symfony2?

Lowgrade answered 3/3, 2013 at 16:41 Comment(1)
Now you can do this with swiftmailer v2.3.3+: #16475322Zoellick
W
7

There is no default symfony way to have 2 different instances. But you can just make a new class that extends swiftmailer, make it to be a service and just pass to the parent constructor your different configuration.

Washerwoman answered 3/3, 2013 at 17:23 Comment(2)
Really?!?! Omg, this is insane! By the way... I'll follow your suggestions!Lowgrade
There should be something like for the entity managers! One can defined multiple entity managers... it would be nice to define multiple Swiftmailer instances!Lowgrade
B
4
swiftmailer:
    default_mailer: second_mailer
    mailers:
        first_mailer:
        # ...
        second_mailer:
        # ...

// ...

// returns the first mailer
$container->get('swiftmailer.mailer.first_mailer');

// also returns the second mailer since it is the default mailer
$container->get('swiftmailer.mailer');

// returns the second mailer
$container->get('swiftmailer.mailer.second_mailer');

http://symfony.com/doc/current/reference/configuration/swiftmailer.html#using-multiple-mailers

Brower answered 29/3, 2016 at 22:56 Comment(3)
I think you're missing a tab from the second config line.Grote
2.1 is very old. You need considering an update perhaps.Brower
I found a way by creating different environments. Since I would call the second account for a Command, that works fine as long as I add --env=OTHER_ENV after the call.Grote

© 2022 - 2024 — McMap. All rights reserved.