1.在common/main-local.php中配置Mailer
return [ 'components' => [ .... 'mailer' => [ 'class' => 'yiiswiftmailerMailer', 'useFileTransport' =>false,//这句一定有,false发送邮件,true只是生成邮件在runtime文件夹下,不发邮件 'viewPath' => '@common/mail', 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'smtp.163.com', //每种邮箱的host配置不一样, 这里是163邮箱的写法 'username' => 'ABC@163.com', //一般是自己网站的邮箱,自己修改 'password' => '123456', //这里填写的不是登录邮箱的密码, 是邮箱里设置的客户端授权密码 'port' => '25', 'encryption' => 'tls', ], 'messageConfig'=>[ 'charset'=>'UTF-8', 'from'=>['ABC@163.com'=>'admin'] ], ], ] ]
2. 测试代码:
public function actionSendEmail(){ return Yii::$app->mailer->compose() ->setTo('123@163.com') ->setFrom(['ABC@163.com'=>'admin']) //这里的SendFrom与设置里的 messageConfig => from 一致, 或者不写这行. ->setSubject('this is subject') ->setTextBody('this is body') ->send(); }
ABC@163里要开启服务,并设置授权密码(如上面的123456):