Inject SwiftMailer into symfony2 service

Depending on what kind of service file you are using you need to inject it into your service directly like you said.

XML:

<services>
        <service id="sample.service" class="%sample.service.class%">
            <argument type="service" id="mailer" />
        </service>
</services>

YAML:

services:
    sample.service:
        class:     %sample.service.class%
        arguments: [@mailer]

You can simply grab the service in your constructor like this. Or if you really want, you can inject the service_container. But that's really dirty, since you can just inject the services you need.

Injection the service_container is only needed if you need a dynamic service call.


In services.yml (symfony 4 example)

mailer:
    class: \Swift_Mailer

myClass:
    class: x\x
    arguments:
        - "@mailer"