在yii2框架中基于swiftmailer和redis编写自定义异步发送邮件的插件,并提交到composer
1、在vendor中创建目录结构如下:
lvfk 此文件夹下可以由多个插件
└── mailerqueue 插件名称
└── src 存放插件源码
├── Mailer.php 继承\yii\swiftmailer\Mailer,自定参数并正真发送Redis中存储的邮件
└── Message.php 继承\yii\swiftmailer\Message,改写原有发送邮件功能为存储到Redis列表中
1、在vendor中创建目录结构如下:
lvfk 此文件夹下可以由多个插件
└── mailerqueue 插件名称
└── src 存放插件源码
├── Mailer.php 继承\yii\swiftmailer\Mailer,自定参数并正真发送Redis中存储的邮件
└── Message.php 继承\yii\swiftmailer\Message,改写原有发送邮件功能为存储到Redis列表中
2、编写Mail.php 和 Message.php
Message.php
<?php
/**
* Message.php.
* User: lvfk
* Date: 2018/2/3 0003
* Time: 16:40
* Desc:
*/
namespace lvfk\mailerqueue;
use yii\base\InvalidConfigException;
class Message extends \yii\swiftmailer\Message
{
/**
* 存储邮件到redis队列中
* @return mixed
* @throws InvalidConfigException
*/
public function queue(){
//检测redis
$redis = \Yii::$app->redis;
if(empty($redis)){
throw new InvalidConfigException('redis not found in config');
}
//检测mailer
$mailer = \Yii::$app->mailer;
if(empty($redis) || !$redis->select($mailer->db) || empty($mailer->key)){
throw new InvalidConfigException('mailer not found in config');
}
if(empty($mailer->key)){
throw new InvalidConfigException('parameter key not found in mailer config');
}
if(!$redis->select($mailer->db)){
throw new InvalidConfigException('parameter db not found in mailer config');
}
//发送
$message = [];
$message['from'] = array_keys($this->from);
$message['to'] = array_keys($this->getTo());
$message['cc'] = !empty($this->getCc())?array_keys($this->getCc()):[];
$message['bcc'] = !empty($this->getBcc())?array_keys($this->getBcc()):[];
$message['reply_to'] = !empty($this->getReplyTo())?array_keys($this->getReplyTo()):[];
$message['charset'] = $this