Yii2邮箱发送与配置

1配置邮箱

在 common/config/web.php中写入以下代码配置 Mail代理

 return [
        'components' => [
            ...//your code,
            //以下是 mail 的配置
            'mailer' => [
                'class' => 'yiiswiftmailerMailer',
                'viewPath' => '@common/mail',
                'transport' => [
                    'class' => 'Swift_SmtpTransport',
                    //我用的是QQ 的代理,所以这里是 QQ 的配置信息
                    'host' => 'smtp.qq.com',
                    'port' => 587,
                    'encryption' => 'tls',    
                    //这部分信息不应该公开,所以后期会由数据库中拿取
                    'username' => '你的 QQ 号',
                    'password' => '在开启SMTP服务后,生成de一个授权码,不是扣扣密码',
                ],
                //发送的邮件信息配置
                'messageConfig' => [

                    'charset' => 'utf-8',

                    'from' => ['410345759@qq.com' => '祝云']
                ],

            ],'

        ]

    ];

2接下来就可以发送邮件了

   不使用模板
    $mail = Yii::$app->mailer->compose();
    $mail->setTo('发送的邮箱');
    $mail->setSubject('邮件的标题');
    $mail->setHtmlBody('邮件内容,这里可以使用 HTML 代码');
    $mail->send();//发送

    使用模板           //你也可以在 compose() 方法中传递一些视图所需参数,这些参数可以在视图文件中使用
Yii::$app->mailer->compose(
'模板文件名称',['key' => $value])
     ->setFrom('from@domain.com')
  ->setTo('to@domain.com')
   ->setSubject('Message subject')
   ->setTextBody('Plain text content')
   ->setHtmlBody('<b>HTML content</b>')
   ->send();
//compose 与控制器中的 render 方法参数方式相同.

问题当出现:

Failed to authenticate on SMTP server with username "1710000" using 1 possible authenticators

   1、在邮箱设置中开启SMTP服务

   2、在开启SMTP服务后,生成一个授权码,填入配置文件的  password 即可。

 2016-11-13 18:48:15

原文地址:https://www.cnblogs.com/webph/p/6059480.html