Search code examples
emailyii2smtpmailer

yii2 mailer smtp connection refused


When setting up my smtp mailer in the config file, it works fine. But if I manually create the SMPT mailer it fails (Connection refused). Can anybody assist?

Yii2 config file:

'components'=[
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.gmail.com',  
                'username' => '[email protected]',
                'password' => 'password',
                'port' => '587', 
                'encryption' => 'tls', 
            ],

The following code in my controller does not work:

$mailer = new \yii\swiftmailer\Mailer();
$mailer->transport = new \Swift_SmtpTransport();
$mailer->transport
    ->setHost('smtp.gmail.com')
    ->setPort(587)
    ->setEncryption('tls');
$mailer->transport->setUsername('[email protected]');
$mailer->transport->setPassword('password');

and I receive an error message: Connection refused #111

I have tried port 465 on ssl and I receive the same message.

My main reason for doing this is that I have different client accounts, each of which has its own smtp. I therefore need one account per client and I cannot seem to do that via the config file.

Many thanks for your help.


Solution

  • I just tried it worked for me, I did as follow

    'components'=[
        'mailer' => [  //Your default mailer
            'class' => 'yii\swiftmailer\Mailer',
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.gmail.com',  
                'username' => '[email protected]',
                'password' => 'password',
                'port' => '587', 
                'encryption' => 'tls', 
            ],
        ],
    'mailer2' => [  //Your custom mailer
            'class' => 'yii\swiftmailer\Mailer',
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.gmail.com',  
                'username' => '[email protected]',
                'password' => 'new_password',
                'port' => 'new_port587', 
                'encryption' => 'new_tls', 
            ],
        ]
    

    following is for default config

     Yii::$app->mailer->compose()
            ->setFrom('[email protected]')
            ->setTo('[email protected]')
            ->setSubject('Subject')
            ->setTextBody('Plain text content')
            ->setHtmlBody("Hello")
            ->send();
    

    following with custom mailer config

     Yii::$app->mailer2->compose()
            ->setFrom('[email protected]')
            ->setTo('[email protected]')
            ->setSubject('Subject')
            ->setTextBody('Plain text content')
            ->setHtmlBody("Hello")
            ->send();
    

    create a component is the fastest solution, otherwise, you can use the parameter to store configuration, and call when needed.