codexten / yii-mailqueue
该包的最新版本(dev-master)没有提供许可证信息。
Codexten Yii 邮件队列
dev-master / 2.0.x-dev
2019-03-16 09:27 UTC
Requires
- codexten/yii-core: ~2.0
- katzgrau/klogger: ~1.2.1
- yiisoft/yii2-swiftmailer: ~2.0.7
This package is auto-updated.
Last update: 2024-09-16 22:23:21 UTC
README
为 Yii 2.0 或更高版本提供的 Yii 邮件队列
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();