EmailGroupSend.php
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace App\Console\Commands\Task;
use App\Mail\TextMail;
use App\Models\Subscribe\GroupSendTask;
use App\Models\Subscribe\GroupSendTaskLog;
use App\Models\Subscribe\Smtp;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
/**
*
* Class TaskDistribution
* @package App\Console\Commands
* @author zbj
* @date 2023/11/28
*/
class EmailGroupSend extends Command
{
protected $signature = 'email_group_send_task';
protected $description = '邮件群发任务';
public function handle()
{
while (true) {
$tasks = GroupSendTask::where('status', GroupSendTask::STATUS_PENDING)->where('send_time', '<=', time())->get();
if (!$tasks->count()) {
sleep(10);
}
foreach ($tasks as $task) {
$this->toQueue($task);
}
}
}
public function toQueue(GroupSendTask $task)
{
$this->output('开始执行任务:' . $task->id);
$smtp_config = Smtp::where('project_id', $task->project_id)->first();
if (!$smtp_config) {
$task->status = GroupSendTask::STATUS_ERROR;
$task->remark = '未配置SMTP';
$task->save();
$this->output('任务:' . $task->id . '失败,未配置SMTP');
return false;
}
Config::set('mail.mailers.smtp.host', $smtp_config['host']);
Config::set('mail.mailers.smtp.username', $smtp_config['email']);
Config::set('mail.mailers.smtp.password', $smtp_config['password']);
Config::set('mail.from.address', $smtp_config['email']);
Config::set('mail.from.name', $smtp_config['from_name']);
foreach ($task->emails as $email) {
try {
Mail::to([$email])->send(new TextMail(['subject' => $task->subject, 'text' => $task->text]));
GroupSendTaskLog::addLog($task->id, $task->project_id, $smtp_config['email'], $email);
} catch (\Exception $e) {
GroupSendTaskLog::addLog($task->id, $task->project_id, $smtp_config['email'], $email, 2, $e->getMessage());
$this->output('任务:' . $task->id . ' 邮箱' . $email . '发送失败,' . $e->getMessage());
}
}
$task->status = GroupSendTask::STATUS_SUCCESS;
$task->save();
}
/**
* 输出处理日志
*/
public function output($message): bool
{
echo date('Y-m-d H:i:s') . ' | ' . $message . PHP_EOL;
return true;
}
}