Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple instances of Swiftmailer in Symfony2

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?

like image 691
JeanValjean Avatar asked Mar 03 '13 16:03

JeanValjean


2 Answers

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.

like image 166
Hast Avatar answered Nov 11 '22 10:11

Hast


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

like image 30
Altynbek Usenov Avatar answered Nov 11 '22 11:11

Altynbek Usenov