nterms / yii2-mailqueue
适用于 yii2 的电子邮件队列组件,与 yii2-swiftmailer 配合使用。
0.0.16
2018-11-26 16:44 UTC
Requires
- yiisoft/yii2: *
- yiisoft/yii2-swiftmailer: ~2.1.0
README
适用于 yii2 的电子邮件队列组件,与 yii2-swiftmailer 配合使用。
安装
安装此扩展的首选方法是通过 composer。
运行以下命令:
php composer.phar require --prefer-dist nterms/yii2-mailqueue "*"
或者将以下内容添加到您的 composer.json
文件的 require 部分:
"nterms/yii2-mailqueue": "*"
配置
扩展安装后,将以下代码添加到您的应用程序配置中:
return [ //.... 'components' => [ 'mailqueue' => [ 'class' => 'nterms\mailqueue\MailQueue', 'table' => '{{%mail_queue}}', 'mailsPerRound' => 10, 'maxAttempts' => 3, ], ], ];
以下属性可用于自定义邮件队列行为。
table
:存储添加到队列中的电子邮件的数据库表名。mailsPerRound
:一次发送的电子邮件数量。maxAttempts
:每封电子邮件的最大发送尝试次数。
更新数据库架构
将以下代码添加到 /config/console.php
中以应用数据库迁移以创建存储邮件队列消息所需的表。
return [ //.... 'components' => [ 'mailqueue' => [ 'class' => 'nterms\mailqueue\MailQueue', 'table' => '{{%mail_queue}}', ], ], ];
然后,在命令行中运行 yii migrate
命令。
php yii migrate/up --migrationPath=@vendor/nterms/yii2-mailqueue/migrations/
处理邮件队列
现在,在 Yii::$app->mailqueue
上调用 process()
将处理消息队列并发送电子邮件。在您的控制器操作之一中
public function actionSend() { Yii::$app->mailqueue->process(); }
最好是控制台命令(例如:mail/send),它可以由 CRON 作业触发。
设置 CRON 作业
设置运行控制台命令的 CRON 作业
*/10 * * * * php /var/www/html/myapp/yii mailqueue/process
用法
然后,您可以按照以下方式将电子邮件发送到队列:
Yii::$app->mailqueue->compose('contact/html') ->setFrom('from@domain.com') ->setTo($form->email) ->setSubject($form->subject) ->setTextBody($form->body) ->queue();
虽然 nterms\mailqueue\MailQueue
继承自 yii\swiftmailer\Mailer
,但您可以通过直接将 yii2-swiftmailer
配置添加到 mailqueue
配置中来替换此扩展,如下所示:
return [ //.... 'components' => [ 'mailqueue' => [ 'class' => 'nterms\mailqueue\MailQueue', 'table' => '{{%mail_queue}}', 'mailsPerRound' => 10, 'maxAttempts' => 3, 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'localhost', 'username' => 'username', 'password' => 'password', 'port' => '587', 'encryption' => 'tls', ], ], ], ];
并且使用以下代码直接发送电子邮件,就像您通常使用 yii2-swiftmailer
一样:
Yii::$app->mailqueue->compose('contact/html') ->setFrom('from@domain.com') ->setTo($form->email) ->setSubject($form->subject) ->setTextBody($form->body) ->send();