事件 邮件发送 - 408824338/test-yii2 GitHub Wiki

##访问地址 http://ysk.dev/admin/demo-send-mail/send

控制器

地址:backend/controllers/DemoSendMailController.php

class DemoSendMailController extends Controller {

    const SEND_MAIL = 'send_mail';

    public function init() {
        parent::init();
        $this->on(self::SEND_MAIL, ['backend\components\Mail', 'sendMail']);

    }

    /**
     * 1.配置里添加 mailer组件类
     * 2.添加组件 Mail类
     * 3.添加event类 MailEvent
     * @author cmk
     */
    public function actionSend() {
        try {
            $event = new MailEvent();
            $event->email = '[email protected]';
            $event->subject = '测试事件邮件标题2';
            $event->content = '测试的事件的内容2';
            $this->trigger(self::SEND_MAIL, $event);
            echo '发送成功';
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
}

##自定义的邮件类 地址:backend/components/Mail.php

class Mail {

    public static function sendMail($event) {
        $mail = \Yii::$app->mailer->compose();
        $mail->setTo($event->email);//要发送给那个人的邮箱
        $mail->setSubject($event->subject);//邮件主题
        $mail->setTextBody($event->content);//发布纯文字文本
        return $mail->send();
    }

}

##事件类 地址:backend/components/event/MailEvent.php

use yii\base\Event;

class MailEvent extends Event {

    public $email;
    public $subject;
    public $content;
    
}

##配置添加组件mailer 地址:backend/config/web.php

'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            // 这个要设置为false,才会真正的发邮件
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                // 如果是163邮箱,host改为smtp.163.com
                'host' => 'smtp.qq.com',
                // 邮箱登录帐号
                'username' => '[email protected]',
                // 如果是qq邮箱,这里要填写第三方授权码,而不是你的qq登录密码,参考qq邮箱的帮助文档
                //http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
                'password' => 'hlbzsiaytqtlbjjj',
                'port' => '25',
                'encryption' => 'tls',
            ],
            'messageConfig'=>[
                'charset'=>'UTF-8',
                'from'=>['[email protected]'=>'cmk-mail-test']
            ],
        ],

```
⚠️ **GitHub.com Fallback** ⚠️