Joshi
Joshi

Reputation: 2790

Yii2 - Setting Mailer Transport parameters on runtime

I am trying to set the configuration for the Mailer, for example in basic template config/web.php i have added below.

$config = [
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'testmailhost.com', // want to replace with $mail_host
                'username' => '[email protected]',
                'password' => 'testing111',
                'port' => '587',
                'encryption' => 'tls'
            ]
        ]
    ]
];

Now I want to set the values for host, username, password port etc stored in database table settings. so how can replace these values here.

I have created a component which I can access the values as

$st = Yii::$app->getTable;
$mail_host = $st->settings('general', 'mail_host');

Upvotes: 0

Views: 1506

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23778

The Yii2 Mailer class provides you with a public method named setTransport to which you can pass the transport config array as param.

In the config just add the mailer component configurations and add the transport configurations via your custom component.

$config = [
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'useFileTransport' => false,
        ]
    ]
];

See the below code, you can use it in your component now to add the transport configurations from your database.

Yii::$app->mailer->setTransport(
        [
            'class' => 'Swift_SmtpTransport',
            'host' => 'localhost', 
            'username' => 'username',
            'password' => 'password',
            'port' => '587', 
            'encryption' => 'tls'
        ]
    );

Hope this helps.

Upvotes: 3

Related Questions