Yii2 Setting up email

<note>This is based on Yii2 Advanced Application template.</note>

Configuration (Multiple)

In file common/config/main-local.php set 'useFileTransport' ⇒ false from the default of true

Update common/config/main-local.php to include below where two configurations are used.

        'mailerGmail' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.gmail.com',
                'username' => 'USER@gmail.com',
                'password' => 'PASSWORD',
                'port' => '587',
                'timeout' => 5,
                'encryption' => 'tls',
            ],
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => '192.168.1.20',
                //'username' => 'user@domain.fr',
                //'password' => '*******',
                'port' => '25',
                'timeout' => 5,
               // 'encryption' => 'tls',
            ],
        ],

Choosing which Mail Configuration to use

In common/config/params-local.php define mailer as below

<?php
return [
    'mailopt' => 'mailer',
    'mailoptbatch' => 'mailer',
    //'mailopt' => 'mailerGmail',
    //'mailopt' => 'mailerGmail1',
    'adminEmail' => 'system@example.org',
    'supportEmail' => 'support@example.org',
    'noreplyEmail' => 'noreply@example.org',
    'senderEmail' => 'yesreply@example.org',
    'senderName' => 'example.org mailer',
];

Then when using mail function do the below:

        $mailopt = Yii::$app->params['mailopt'];
        return Yii::$app->$mailopt->compose()
            ->setTo($email)
            ->setFrom([Yii::$app->params['senderEmail'] => Yii::$app->params['senderName']])
            ->setReplyTo([$this->email => $this->name])
            ->setSubject(Yii::$app->params['emailSubjectPrefix'] . $this->subject)
            ->setTextBody($this->body)
            ->send();

QR Code
QR Code tech:yii2:mail_setup (generated for current page)