Symfony 3.4: Changing SwiftMailer's smtp settings

I am fairly new to Symfony. We are using Symfony 3.4 and the FOSUserBundle. This client would like to specify their own smtp server settings (host, port, password, etc.) through an interface and stored in a database table. I researched ways to go about this and found this promising thread doing exactly that with an event listener (Mun Mun Das's answer):

Changing smtp settings in SwiftMailer dynamically

Unfortunately, I think this was untested code and I am having trouble implementing it. I tried many things to work around the current issue but decided to start again. After a first few obvious fixes to that code my listener looks like:


namespace AppBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class SwiftMailerListener implements EventSubscriberInterface

    private $transport;
    private $em;

    public function __construct($transport, $em)
        $this->transport = $transport;
        $this->em = $em;

    public function onKernelRequest(GetResponseEvent $event)

    static public function getSubscribedEvents()
        return array(
            KernelEvents::REQUEST => array('onKernelRequest', 0)


and the relevant portion in services.yml:

    class: AppBundle\EventListener\SwiftMailerListener
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
    arguments: ["@swiftmailer.transport.real", "@doctrine.orm.entity_manager"]         

This gives me the error:

(1/1) RuntimeException Cannot autowire service
"AppBundle\EventListener\SwiftMailerListener": argument "$transport" 
of method "__construct()" must have a type-hint or be given a value

I'm now struggling to figure out what type-hint to use (still getting a grasp of the Symfony "lay of the land") and why it is necessary here but not in the example.

Any ideas for a fix, appropriate avenue of research, or even an alternative approach to what I'm trying to accomplish?

2 answers

  • answered 2018-06-15 21:41 Yosra Hamza

    If you are defining your service in a service.yml file under your bundle's folder, try to move it to the main services file "app/config/services.yml", see this link

  • answered 2018-06-16 19:04 nic

    Maybe it cannot find swiftmailer.transport.real.

    Try to use just @mailer And in symfony 3.4 you can use just dependency injection and autowiring.

    If you want to change host and port dynamically you can use enviroment variables that already exists in symfony 3.4. You can easily change them dynamically. If you dont want to change it dynamically, you can put host and port and everything else in the parameters.yml where is mail configuration.