szelest / yii2-mailqueue
为yii2提供的电子邮件队列组件,与yii2-swiftmailer兼容。
dev-master
2023-01-16 14:08 UTC
Requires
- php: >=7.4
- yiisoft/yii2: *
- yiisoft/yii2-swiftmailer: ~2.1.0
This package is auto-updated.
Last update: 2024-09-16 18:11:05 UTC
README
为yii2提供的电子邮件队列组件,与yii2-swiftmailer兼容。
安装
安装此扩展的首选方法是通过 composer。
运行以下命令
php composer.phar require --prefer-dist szelest/yii2-mailqueue "dev-master"
或者
"szelest/yii2-mailqueue": "dev-master"
将以下内容添加到您的 composer.json
文件的 require 部分。
配置
扩展安装完成后,将以下代码添加到您的应用程序配置中
return [ //.... 'components' => [ 'mailqueue' => [ 'class' => 'szelest\mailqueue\MailQueue', 'table' => '{{%mail_queue}}', 'mailsPerRound' => 10, 'maxAttempts' => 3, ], ], ];
以下属性可用于自定义邮件队列行为。
table
:存储添加到队列中的电子邮件的数据库表名。mailsPerRound
:每次发送的电子邮件数量。maxAttempts
:每个电子邮件的最大发送尝试次数。
更新数据库模式
将以下代码添加到 /config/console.php
以应用数据库迁移以创建存储邮件队列消息所需的表。
return [ //.... 'components' => [ 'mailqueue' => [ 'class' => 'szelest\mailqueue\MailQueue', 'table' => '{{%mail_queue}}', ], ], ];
然后在命令行中运行 yii migrate
命令
php yii migrate/up --migrationPath=@vendor/szelest/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();
虽然 szelest\mailqueue\MailQueue
继承自 yii\swiftmailer\Mailer
,但您可以通过以下方式将其替换为该扩展,即将 yii2-swiftmailer
配置直接添加到 mailqueue
配置中,如下所示
return [ //.... 'components' => [ 'mailqueue' => [ 'class' => 'szelest\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();