Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2.3: How do you configure SwiftMailer to automatically use a custom plugin?

I have created a custom SwiftMailer plugin which I would like to have SwiftMailer use by default in my Symfony 2.3 application. The only documentation I can find in this regard is here: http://symfony.com/doc/current/reference/dic_tags.html#swiftmailer-plugin

I have set up the service as follows:

acme_test_bundle.swiftmailer.embed_images:
    class: Acme\TestBundle\SwiftMailer\Plugins\ImageEmbedPlugin
    tags:
        - { name: swiftmailer.plugin }

SwiftMailer is not using the plugin even though this service has been created. Have I done something wrong and is there anything else I should be doing?

like image 245
Nada_Surf Avatar asked Oct 23 '13 13:10

Nada_Surf


2 Answers

I managed to figure this out myself.

Contrary to what the Symfony 2.3 documentation says, you need to tag the service with which mailer you will be using (usually the 'default' one).

Therefore, I needed to change swiftmailer.plugin to swiftmailer.default.plugin

So, the service definition is now:

acme_test_bundle.swiftmailer.embed_images:
    class: Acme\TestBundle\SwiftMailer\Plugins\ImageEmbedPlugin
    tags:
        - { name: swiftmailer.default.plugin }
like image 105
Nada_Surf Avatar answered Oct 18 '22 02:10

Nada_Surf


To provide some additional context to the OP's answer.

As of Symfony 2.3 in the SwiftmailerBundle CompilerPass process it performs the following.

$mailers = $container->getParameter('swiftmailer.mailers');
foreach ($mailers as $name => $mailer) {
      $plugins = $container->findTaggedServiceIds(sprintf('swiftmailer.%s.plugin', $name));
       foreach ($plugins as $id => $args) {
            $transport->addMethodCall('registerPlugin', [new Reference($id)]);
       }
}

Based on this you would need to add all of the mailer names to your tags that you would like to add the plugin to, in the format of swiftmailer.%mailer_name%.plugin. Replacing %mailer_name% with the name of your mailers.

When not using the multiple mailers configuration for swiftmailer the %mailer_name% is default which is set in the Bundle Configuration.

$v['default_mailer'] = isset($v['default_mailer']) ? (string) $v['default_mailer'] : 'default';
$v['mailers'] = array($v['default_mailer'] => $mailer);

Example config.yml

swiftmailer:
    default_mailer: first_mailer #alias: default
    mailers:
      first_mailer:
        #...
      second_mailer:
        #...


    services:
        #...
        swiftmailer.plugin.array_logger:
            class: Swift_Plugins_Loggers_ArrayLogger
        swiftmailer.plugin.logger:
            class: Swift_Plugins_LoggerPlugin
            arguments: ['@swiftmailer.plugin.array_logger']
            tags:
                - { name: swiftmailer.default.plugin }
                - { name: swiftmailer.second_mailer.plugin }
like image 42
Will B. Avatar answered Oct 18 '22 02:10

Will B.