Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Swiftmailer transport options dynamically instead of using parameters.yml options

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);
like image 644
BentCoder Avatar asked Oct 08 '14 10:10

BentCoder


1 Answers

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);
like image 160
BentCoder Avatar answered Nov 16 '22 19:11

BentCoder