dantart/yii2-mailqueue

为 yii2 使用的邮件队列组件,与 yii2-swiftmailer 兼容。

安装: 130

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 49

类型:yii2-extension

v0.0.15 2017-04-03 08:41 UTC

This package is not auto-updated.

Last update: 2024-09-29 03:04:50 UTC


README

为 yii2 使用的邮件队列组件,与 yii2-swiftmailer 兼容。

安装

安装此扩展的首选方式是通过 composer

运行以下命令

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

"dantart/yii2-mailqueue": "*"

将其添加到您的 composer.json 文件的 require 部分。

配置

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

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/

处理邮件队列

现在调用 process()Yii::$app->mailqueue 将处理消息队列并发送电子邮件。在您的控制器动作之一中

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