Mailing in Yii2 Demo Code

{ Plan A. Direct Send from Server }

{ Step 1. Config }

return [
    //....
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
        ],
    ],
];

 

{ Step 2. Send }

$mailer = \Yii::$app->mailer->compose();
$mailer->setFrom($from);
$mailer->setTo($to);
$mailer->setSubject($subject);
$mailer->setTextBody($body);//text
$mailer->setHtmlBody($body);//html
$mailer->send();

 

{ Plan B. User 3'rd Part SMTP Send }

use http://mail.163.com as demo

check SMTP Params here : 

163 : http://help.163.com/09/1221/08/5R1VKBKA00753VB9.html?servCode=6020378

Gmail : https://support.google.com/a/answer/176600

{ Step 1. Config }

'mailer' => [  

  'class' => 'yii\swiftmailer\Mailer',  
  'useFileTransport' =>false,//必填!! false表示发送邮件, true表示存在runtime文件包下

  'transport' => [  
    'class' => 'Swift_SmtpTransport',  
    'host' => 'smtp.163.com',  //SMTP config
    'username' => 'Boy.Lee@163.com', //SMTP config
    'password' => '*******',//SMTP config
    'encryption' => 'tls',  //SMTP config
    'port' => '25',  //SMTP config
                   
  ], 

  'messageConfig'=>[  
    'charset'=>'UTF-8',  
    'from'=>['Boy.Lee@163.com'=>'Boy.Lee']  
  ],  
],  

 

{ Step 2. Send }

$mailer = \Yii::$app->mailer->compose();
$mailer->setFrom($from);
$mailer->setTo($to);
$mailer->setSubject($subject);
$mailer->setTextBody($body);//text
$mailer->setHtmlBody($body);//html
$mailer->send();

 

Plan C. User 3'rd Part Mail sender }

Here we use MailGun as example, Link: YII 2.0 USE MAILGUN API SEND EMAIL