adantart / yii2-mailqueue

yii2的邮件队列组件,与yii2-swiftmailer协同工作。

安装: 38

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 0

开放问题: 0

类型:yii2-extension

dev-master 2019-09-18 15:27 UTC

This package is auto-updated.

Last update: 2024-09-19 01:58:37 UTC


README

yii2的邮件队列组件,与yii2-swiftmailer协同工作。

安装

推荐通过composer安装此扩展。

运行以下命令:

php composer.phar require --prefer-dist dantart/yii2-mailqueue "*"

或者将以下内容添加到你的composer.json文件的require部分:

"dantart/yii2-mailqueue": "*"

```json

配置

扩展安装后,将以下代码添加到你的应用程序配置文件中

return [
    //....
    'components' => [
        'mailqueue' => [
            'class' => 'dantart\mailqueue\MailQueue',
			'table' => '{{%mail_queue}}',
			'mailsPerRound' => 10,
			'maxAttempts' => 3,
        ],
    ],
];

以下属性可用于自定义邮件队列行为。

  • table:存储添加到队列中的邮件的数据库表名称。
  • mailsPerRound:每次发送的邮件数量。
  • maxAttempts:每封邮件的最大发送尝试次数。

更新数据库模式

应用数据库迁移以创建存储邮件队列消息所需的表。为此,将以下代码添加到/config/console.php

return [
    //....
    'components' => [
        'mailqueue' => [
            'class' => 'dantart\mailqueue\MailQueue',
			'table' => '{{%mail_queue}}',
        ],
    ],
];

然后在命令行中运行yii migrate命令

php yii migrate/up --migrationPath=@vendor/dantart/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();

虽然dantart\mailqueue\MailQueue继承自yii\swiftmailer\Mailer,但你可以通过以下方式将此扩展替换为直接将yii2-swiftmailer配置添加到mailqueue配置中:

return [
    //....
    'components' => [
        'mailqueue' => [
            'class' => 'dantart\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();

许可

MIT