Yii2.0 事件使用和发送邮件实例

开启邮件服务(这里是QQ邮箱)

登录邮箱->设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务->开启 POP3/SMTP服务->复制 授权码

配置Yii2.0邮件

common/config/main-local.php

    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'viewPath' => '@common/mail',
        'useFileTransport' => false,// 设置为false,才会发邮件
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.qq.com',// 每种邮箱host配置不一样如果是163邮箱,host改为smtp.163.com
            'username' => '327083961@qq.com',// 用于发送的账号
            'password' => '*****',// 授权码
            'port' => '25',
            'encryption' => 'tls',
        ],
        'messageConfig'=>[
            'charset'=>'UTF-8',
            'from'=>['327083961@qq.com'=>'icand']// 邮件会显示谁发送的
        ],
    ],

新建发送的 Mail 类

common/components/Mail.php

namespace backend\components;

use \yii\base\Component;

class Mail
{
    public static function sendMail ($event)
    {
	    $mail = \Yii::$app->mailer->compose();

	    $mail->setTo($event->email);// 要发送给那个人的邮箱
	    $mail->setSubject($event->subject); // 邮件主题
	    $mail->setTextBody($event->content); // 邮箱内容

        $event->valid = $mail->send(); // 发送与否  成功1  失败0

        return $event->valid;
    }
}

绑定事件 和 触发事件

邮件控制器: backend/controllers/SendMailController.php

namespace common\controllers;

use yii\web\Controller;
use common\components\Mail;
use common\components\event\MailEvent;

class SendMailController extends Controller
{
	const SEND_MAIL = 'send_mail';

	public function init()
	{
		parent::init();
		$mail = new Mail;

		// 绑定send_mail这个事件 (调用我们刚刚定义的邮件类Mail的sendMial方法)
		$this->on(self::SEND_MAIL, [$mail, 'sendMail']);
		// 绑定匿名函数
		// $this->on(self::SEND_MAIL, function(){

			});

		// 取消绑定
		// $this->off(self::SEND_MAIL, [$mail, 'sendMail'])
	}

	public function actionSend()
	{
		// 触发邮件事件
		$event = new MailEvent;

		$event->email   = '2218387221@qq.com';
		$event->subject = "邮件事件测试";
		$event->content = "我是123!!!!!";

		// $this->trigger(self::SEND_MAIL);
		$this->trigger(self::SEND_MAIL,$event);

		if ($event->valid) {
			echo "发送成功";
		}else{
			echo "发送失败";
		}
	}
}

$event 触发事件的时候, 会把$event对象传递给 Mail类

定义邮件事件

新建: common/components/event/MailEvent.php

namespace common\components\event;

use yii\base\Event;

class MailEvent extends Event
{
    public $email; // 发送给谁
    public $subject;// 邮件主题
    public $content;// 邮件内容

    public $valid;// 用于判断发送成功或者失败

    //... 扩展
    //... 扩展
    //... 扩展
}

参考:

-http://www.manks.top/document

-http://www.imooc.com/video/9644/0

-http://www.yiichina.com/tutorial/320

-http://www.yiifans.com/yii2/guide/concept-events.html




导航