Overriding Swiftmailer transport options dynamically instead of using parameters.yml options
Asked Answered
R

1

5

Code below works fine when sending emails by default however I want to override SwiftMailer transport options (host, user and password) before sending the email and the options will be coming from database.

Anyone know how to achieve this?

Note: I went thru this post but the listener didn't do anything and the OP's solution has $transport->getExtensionHandlers(); method which doesn't appear in my $transport object when I dump it.

Composer entry

"symfony/swiftmailer-bundle": "2.1.*"

/booking/app/config/parameters.yml

parameters:
    mailer_transport:  gmail
    mailer_host:       smtp.gmail.com
    mailer_user:       vizzzzz
    mailer_password:   123123

/booking/app/config/config.yml

swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host%"
    username:  "%mailer_user%"
    password:  "%mailer_password%"
    spool:     { type: memory }
    encryption: tls

Controller

$hostDb = $dbObject->getHost();
$userDb = $dbObject->getUser();
$passwordDb = $dbObject->getPassword();

// then I should override setting here so that the data coming from parameters.yml is overriden

$order = // database object

$message = \Swift_Message::newInstance()
    ->setSubject($order->getSubject())
    ->setFrom($order->getFrom())
    ->setTo($order->getTo())
    ->setBody($content)
;
$this->mailer->send($message);
Rodeo answered 8/10, 2014 at 10:48 Comment(0)
R
7

OK I've found it. Doc

// override transport options so that parameters.yml is by-passed
$transport = \Swift_SmtpTransport::newInstance($hostDb,$portDb)
    ->setUsername($userDb)
    ->setPassword($passwordDb)
;

$this->mailer = \Swift_Mailer::newInstance($transport);
// end

$order = // database object

$message = \Swift_Message::newInstance()
    ->setSubject($order->getSubject())
    ->setFrom($order->getFrom())
    ->setTo($order->getTo())
    ->setBody($content)
;
$this->mailer->send($message);
Rodeo answered 8/10, 2014 at 11:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.