修改邮件部分

This commit is contained in:
yinjianm
2026-02-22 03:22:14 +08:00
parent 7a3e245887
commit 17a7c63aec
8 changed files with 206 additions and 71 deletions
+1
View File
@@ -20,6 +20,7 @@ REDIS_PORT=6379
BROADCAST_DRIVER=log BROADCAST_DRIVER=log
CACHE_DRIVER=redis CACHE_DRIVER=redis
QUEUE_CONNECTION=redis QUEUE_CONNECTION=redis
MASS_EMAIL_HOURLY_LIMIT=500
MAIL_DRIVER=smtp MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io MAIL_HOST=smtp.mailtrap.io
@@ -44,14 +44,14 @@ class CommController extends Controller
return $this->fail([400, __('Email verification code has been sent, please request again later')]); return $this->fail([400, __('Email verification code has been sent, please request again later')]);
} }
$code = rand(100000, 999999); $code = rand(100000, 999999);
$subject = admin_setting('app_name', 'XBoard') . __('Email verification code'); $subject = admin_setting('app_name', 'Notification Service') . __('Email verification code');
SendEmailJob::dispatch([ SendEmailJob::dispatch([
'email' => $email, 'email' => $email,
'subject' => $subject, 'subject' => $subject,
'template_name' => 'verify', 'template_name' => 'verify',
'template_value' => [ 'template_value' => [
'name' => admin_setting('app_name', 'XBoard'), 'name' => admin_setting('app_name', 'Notification Service'),
'code' => $code, 'code' => $code,
'url' => admin_setting('app_url') 'url' => admin_setting('app_url')
] ]
@@ -45,11 +45,11 @@ class ConfigController extends Controller
{ {
$mailLog = MailService::sendEmail([ $mailLog = MailService::sendEmail([
'email' => $request->user()->email, 'email' => $request->user()->email,
'subject' => 'This is xboard test email', 'subject' => 'Mail connectivity test',
'template_name' => 'notify', 'template_name' => 'notify',
'template_value' => [ 'template_value' => [
'name' => admin_setting('app_name', 'XBoard'), 'name' => admin_setting('app_name', 'Notification Service'),
'content' => 'This is xboard test email', 'content' => 'This is a mail connectivity test',
'url' => admin_setting('app_url') 'url' => admin_setting('app_url')
] ]
]); ]);
@@ -441,27 +441,32 @@ class UserController extends Controller
ini_set('memory_limit', '-1'); ini_set('memory_limit', '-1');
$sortType = in_array($request->input('sort_type'), ['ASC', 'DESC']) ? $request->input('sort_type') : 'DESC'; $sortType = in_array($request->input('sort_type'), ['ASC', 'DESC']) ? $request->input('sort_type') : 'DESC';
$sort = $request->input('sort') ? $request->input('sort') : 'created_at'; $sort = $request->input('sort') ? $request->input('sort') : 'created_at';
$hourlyLimit = (int) env('MASS_EMAIL_HOURLY_LIMIT', 500);
$hourlyLimit = $hourlyLimit > 0 ? $hourlyLimit : 500;
$builder = User::orderBy($sort, $sortType); $builder = User::orderBy($sort, $sortType);
$this->applyFiltersAndSorts($request, $builder); $this->applyFiltersAndSorts($request, $builder);
$subject = $request->input('subject'); $subject = $request->input('subject');
$content = $request->input('content'); $content = $request->input('content');
$templateValue = [ $templateValue = [
'name' => admin_setting('app_name', 'XBoard'), 'name' => admin_setting('app_name', 'Notification Service'),
'url' => admin_setting('app_url'), 'url' => admin_setting('app_url'),
'content' => $content 'content' => $content
]; ];
$chunkSize = 1000; $chunkSize = 1000;
$processed = 0;
$builder->chunk($chunkSize, function ($users) use ($subject, $templateValue, &$totalProcessed) { $builder->chunk($chunkSize, function ($users) use ($subject, $templateValue, $hourlyLimit, &$processed) {
foreach ($users as $user) { foreach ($users as $user) {
$delaySeconds = intdiv($processed, $hourlyLimit) * 3600;
dispatch(new SendEmailJob([ dispatch(new SendEmailJob([
'email' => $user->email, 'email' => $user->email,
'subject' => $subject, 'subject' => $subject,
'template_name' => 'notify', 'template_name' => 'notify',
'template_value' => $templateValue 'template_value' => $templateValue
], 'send_email_mass')); ], 'send_email_mass'))->delay(now()->addSeconds($delaySeconds));
$processed++;
} }
}); });
+14 -2
View File
@@ -16,6 +16,7 @@ class SendEmailJob implements ShouldQueue
public $tries = 3; public $tries = 3;
public $timeout = 10; public $timeout = 10;
/** /**
* Create a new job instance. * Create a new job instance.
* *
@@ -34,9 +35,20 @@ class SendEmailJob implements ShouldQueue
*/ */
public function handle() public function handle()
{ {
$mailLog = MailService::sendEmail($this->params); $params = $this->params;
if (
$this->queue === 'send_email_mass'
&& isset($params['template_value'])
&& is_array($params['template_value'])
&& array_key_exists('content', $params['template_value'])
) {
$timestamp = now()->format('Y-m-d H:i:s.u');
$params['template_value']['content'] = (string) $params['template_value']['content'] . "\r\n\r\n[Send-Time: {$timestamp}]";
}
$mailLog = MailService::sendEmail($params);
if ($mailLog['error']) { if ($mailLog['error']) {
$this->release(); //发送失败将触发重试 $this->release(60);
} }
} }
} }
+2 -2
View File
@@ -61,11 +61,11 @@ class MailLinkService
SendEmailJob::dispatch([ SendEmailJob::dispatch([
'email' => $user->email, 'email' => $user->email,
'subject' => __('Login to :name', [ 'subject' => __('Login to :name', [
'name' => admin_setting('app_name', 'XBoard') 'name' => admin_setting('app_name', 'Notification Service')
]), ]),
'template_name' => 'login', 'template_name' => 'login',
'template_value' => [ 'template_value' => [
'name' => admin_setting('app_name', 'XBoard'), 'name' => admin_setting('app_name', 'Notification Service'),
'link' => $link, 'link' => $link,
'url' => admin_setting('app_url') 'url' => admin_setting('app_url')
] ]
+172 -55
View File
@@ -54,7 +54,6 @@ class MailService
$progressCallback(); $progressCallback();
} }
// 定期清理内存
if ($statistics['processed_users'] % 2500 === 0) { if ($statistics['processed_users'] % 2500 === 0) {
gc_collect_cycles(); gc_collect_cycles();
} }
@@ -73,14 +72,12 @@ class MailService
$statistics['processed_users']++; $statistics['processed_users']++;
$emailsSent = 0; $emailsSent = 0;
// 检查并发送过期提醒
if ($user->remind_expire && $this->shouldSendExpireRemind($user)) { if ($user->remind_expire && $this->shouldSendExpireRemind($user)) {
$this->remindExpire($user); $this->remindExpire($user);
$statistics['expire_emails']++; $statistics['expire_emails']++;
$emailsSent++; $emailsSent++;
} }
// 检查并发送流量提醒
if ($user->remind_traffic && $this->shouldSendTrafficRemind($user)) { if ($user->remind_traffic && $this->shouldSendTrafficRemind($user)) {
$this->remindTraffic($user); $this->remindTraffic($user);
$statistics['traffic_emails']++; $statistics['traffic_emails']++;
@@ -90,14 +87,13 @@ class MailService
if ($emailsSent === 0) { if ($emailsSent === 0) {
$statistics['skipped']++; $statistics['skipped']++;
} }
} catch (\Exception $e) { } catch (\Exception $e) {
$statistics['errors']++; $statistics['errors']++;
Log::error('发送提醒邮件失败', [ Log::error('发送提醒邮件失败', [
'user_id' => $user->id, 'user_id' => $user->id,
'email' => $user->email, 'email' => $user->email,
'error' => $e->getMessage() 'error' => $e->getMessage(),
]); ]);
} }
} }
@@ -108,15 +104,13 @@ class MailService
*/ */
private function shouldSendExpireRemind(User $user): bool private function shouldSendExpireRemind(User $user): bool
{ {
if ($user->expired_at === NULL) { if ($user->expired_at === null) {
return false; return false;
} }
$expiredAt = $user->expired_at; $expiredAt = $user->expired_at;
$now = time(); $now = time();
if (($expiredAt - 86400) < $now && $expiredAt > $now) { return ($expiredAt - 86400) < $now && $expiredAt > $now;
return true;
}
return false;
} }
/** /**
@@ -131,32 +125,36 @@ class MailService
$usedBytes = $user->u + $user->d; $usedBytes = $user->u + $user->d;
$usageRatio = $usedBytes / $user->transfer_enable; $usageRatio = $usedBytes / $user->transfer_enable;
// 流量使用超过80%时发送提醒
return $usageRatio >= 0.8; return $usageRatio >= 0.8;
} }
public function remindTraffic(User $user) public function remindTraffic(User $user)
{ {
if (!$user->remind_traffic) if (!$user->remind_traffic) {
return; return;
if (!$this->remindTrafficIsWarnValue($user->u, $user->d, $user->transfer_enable)) }
if (!$this->remindTrafficIsWarnValue($user->u, $user->d, $user->transfer_enable)) {
return; return;
}
$flag = CacheKey::get('LAST_SEND_EMAIL_REMIND_TRAFFIC', $user->id); $flag = CacheKey::get('LAST_SEND_EMAIL_REMIND_TRAFFIC', $user->id);
if (Cache::get($flag)) if (Cache::get($flag)) {
return; return;
if (!Cache::put($flag, 1, 24 * 3600)) }
if (!Cache::put($flag, 1, 24 * 3600)) {
return; return;
}
SendEmailJob::dispatch([ SendEmailJob::dispatch([
'email' => $user->email, 'email' => $user->email,
'subject' => __('The traffic usage in :app_name has reached 80%', [ 'subject' => __('The traffic usage in :app_name has reached 80%', [
'app_name' => admin_setting('app_name', 'XBoard') 'app_name' => admin_setting('app_name', 'Notification Service'),
]), ]),
'template_name' => 'remindTraffic', 'template_name' => 'remindTraffic',
'template_value' => [ 'template_value' => [
'name' => admin_setting('app_name', 'XBoard'), 'name' => admin_setting('app_name', 'Notification Service'),
'url' => admin_setting('app_url') 'url' => admin_setting('app_url'),
] ],
]); ]);
} }
@@ -169,48 +167,47 @@ class MailService
SendEmailJob::dispatch([ SendEmailJob::dispatch([
'email' => $user->email, 'email' => $user->email,
'subject' => __('The service in :app_name is about to expire', [ 'subject' => __('The service in :app_name is about to expire', [
'app_name' => admin_setting('app_name', 'XBoard') 'app_name' => admin_setting('app_name', 'Notification Service'),
]), ]),
'template_name' => 'remindExpire', 'template_name' => 'remindExpire',
'template_value' => [ 'template_value' => [
'name' => admin_setting('app_name', 'XBoard'), 'name' => admin_setting('app_name', 'Notification Service'),
'url' => admin_setting('app_url') 'url' => admin_setting('app_url'),
] ],
]); ]);
} }
private function remindTrafficIsWarnValue($u, $d, $transfer_enable) private function remindTrafficIsWarnValue($u, $d, $transfer_enable)
{ {
$ud = $u + $d; $ud = $u + $d;
if (!$ud) if (!$ud) {
return false; return false;
if (!$transfer_enable) }
if (!$transfer_enable) {
return false; return false;
}
$percentage = ($ud / $transfer_enable) * 100; $percentage = ($ud / $transfer_enable) * 100;
if ($percentage < 80) if ($percentage < 80) {
return false; return false;
if ($percentage >= 100) }
if ($percentage >= 100) {
return false; return false;
}
return true; return true;
} }
/** /**
* 发送邮件 * 发送邮件
*
* @param array $params 包含邮件参数的数组,必须包含以下字段:
* - email: 收件人邮箱地址
* - subject: 邮件主题
* - template_name: 邮件模板名称,例如 "welcome" 或 "password_reset"
* - template_value: 邮件模板变量,一个关联数组,包含模板中需要替换的变量和对应的值
* @return array 包含邮件发送结果的数组,包含以下字段:
* - email: 收件人邮箱地址
* - subject: 邮件主题
* - template_name: 邮件模板名称
* - error: 如果邮件发送失败,包含错误信息;否则为 null
* @throws \InvalidArgumentException 如果 $params 参数缺少必要的字段,抛出此异常
*/ */
public static function sendEmail(array $params) public static function sendEmail(array $params)
{ {
$appName = self::sanitizeMailText((string) admin_setting('app_name', config('app.name', 'Notification Service')));
if ($appName === '') {
$appName = 'Notification Service';
}
if (admin_setting('email_host')) { if (admin_setting('email_host')) {
Config::set('mail.host', admin_setting('email_host', config('mail.host'))); Config::set('mail.host', admin_setting('email_host', config('mail.host')));
Config::set('mail.port', admin_setting('email_port', config('mail.port'))); Config::set('mail.port', admin_setting('email_port', config('mail.port')));
@@ -218,32 +215,152 @@ class MailService
Config::set('mail.username', admin_setting('email_username', config('mail.username'))); Config::set('mail.username', admin_setting('email_username', config('mail.username')));
Config::set('mail.password', admin_setting('email_password', config('mail.password'))); Config::set('mail.password', admin_setting('email_password', config('mail.password')));
Config::set('mail.from.address', admin_setting('email_from_address', config('mail.from.address'))); Config::set('mail.from.address', admin_setting('email_from_address', config('mail.from.address')));
Config::set('mail.from.name', admin_setting('app_name', 'XBoard'));
} }
$email = $params['email']; Config::set('mail.from.name', $appName);
$subject = $params['subject'];
$params['template_name'] = 'mail.' . admin_setting('email_template', 'default') . '.' . $params['template_name']; $params['template_value'] = isset($params['template_value']) && is_array($params['template_value'])
? $params['template_value']
: [];
if (array_key_exists('name', $params['template_value'])) {
$params['template_value']['name'] = self::sanitizeMailText((string) $params['template_value']['name']);
} else {
$params['template_value']['name'] = $appName;
}
if ($params['template_value']['name'] === '') {
$params['template_value']['name'] = $appName;
}
if (array_key_exists('content', $params['template_value'])) {
$params['template_value']['content'] = self::sanitizeMailText((string) $params['template_value']['content']);
}
$email = (string) $params['email'];
$subject = self::sanitizeMailText((string) $params['subject']);
if ($subject === '') {
$subject = 'Notification';
}
$originTemplateName = (string) $params['template_name'];
$params['template_name'] = 'mail.' . admin_setting('email_template', 'default') . '.' . $originTemplateName;
$logTemplateName = $params['template_name'];
try { try {
Mail::send( if ($originTemplateName === 'notify') {
$params['template_name'], $html = self::buildModernNotifyHtml($params['template_value'], $subject, $appName);
$params['template_value'], self::sendHtmlMail($email, $subject, $html);
function ($message) use ($email, $subject) { $logTemplateName = 'mail.modern.notify';
$message->to($email)->subject($subject); } else {
} Mail::send(
); $params['template_name'],
$params['template_value'],
function ($message) use ($email, $subject) {
$message->to($email)->subject($subject);
}
);
}
$error = null; $error = null;
} catch (\Exception $e) { } catch (\Throwable $e) {
Log::error($e); Log::error($e);
$error = $e->getMessage(); $error = $e->getMessage();
} }
$log = [ $log = [
'email' => $params['email'], 'email' => $email,
'subject' => $params['subject'], 'subject' => $subject,
'template_name' => $params['template_name'], 'template_name' => $logTemplateName,
'error' => $error, 'error' => $error,
'config' => config('mail') 'config' => config('mail'),
]; ];
MailLog::create($log); MailLog::create($log);
return $log; return $log;
} }
private static function sanitizeMailText(string $text): string
{
$cleaned = str_ireplace(['xboard', 'v2board'], '', $text);
$cleaned = preg_replace('/\s+/', ' ', $cleaned);
return trim((string) $cleaned);
}
private static function escapeHtml(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
private static function buildModernNotifyHtml(array $templateValue, string $subject, string $appName): string
{
$title = self::escapeHtml($subject);
$brand = self::escapeHtml((string) ($templateValue['name'] ?? $appName));
$content = self::escapeHtml((string) ($templateValue['content'] ?? ''));
$content = nl2br($content, false);
$sendTime = self::escapeHtml(now()->format('Y-m-d H:i:s'));
$cta = '';
$url = isset($templateValue['url']) ? (string) $templateValue['url'] : '';
if (filter_var($url, FILTER_VALIDATE_URL)) {
$safeUrl = self::escapeHtml($url);
$cta = '<a href="' . $safeUrl . '" style="display:inline-block;padding:12px 20px;border-radius:10px;background:#111827;color:#ffffff;text-decoration:none;font-weight:600;">Open Link</a>';
}
return '<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>' . $title . '</title>
</head>
<body style="margin:0;padding:0;background:linear-gradient(135deg,#f8fafc 0%,#eef2ff 100%);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;">
<div style="max-width:680px;margin:0 auto;padding:32px 16px;">
<div style="background:#ffffff;border:1px solid #e5e7eb;border-radius:20px;overflow:hidden;box-shadow:0 16px 40px rgba(15,23,42,.08);">
<div style="padding:24px 24px 16px;background:radial-gradient(80% 120% at 0% 0%,#dbeafe 0%,#ffffff 100%);border-bottom:1px solid #e5e7eb;">
<div style="font-size:12px;color:#64748b;letter-spacing:.06em;text-transform:uppercase;">Message</div>
<h1 style="margin:8px 0 0;font-size:24px;line-height:1.3;color:#0f172a;">' . $title . '</h1>
</div>
<div style="padding:24px;">
<div style="font-size:15px;line-height:1.8;color:#334155;">' . $content . '</div>
<div style="margin-top:20px;">' . $cta . '</div>
</div>
<div style="padding:14px 24px;border-top:1px solid #e5e7eb;background:#f8fafc;font-size:12px;color:#64748b;">
<div>Sender: ' . $brand . '</div>
<div>Sent at: ' . $sendTime . '</div>
</div>
</div>
</div>
</body>
</html>';
}
private static function sendHtmlMail(string $email, string $subject, string $html): void
{
$mailer = Mail::getFacadeRoot();
if ($mailer && method_exists($mailer, 'html')) {
Mail::html($html, function ($message) use ($email, $subject) {
$message->to($email)->subject($subject);
});
return;
}
Mail::send([], [], function ($message) use ($email, $subject, $html) {
$message->to($email)->subject($subject);
if (method_exists($message, 'getSymfonyMessage')) {
$symfonyMessage = $message->getSymfonyMessage();
if ($symfonyMessage && method_exists($symfonyMessage, 'html')) {
$symfonyMessage->html($html);
return;
}
}
if (method_exists($message, 'setBody')) {
$message->setBody($html, 'text/html');
return;
}
throw new \RuntimeException('Unsupported mail message driver for html body.');
});
}
} }
+2 -2
View File
@@ -112,10 +112,10 @@ class TicketService
Cache::put($cacheKey, 1, 1800); Cache::put($cacheKey, 1, 1800);
SendEmailJob::dispatch([ SendEmailJob::dispatch([
'email' => $user->email, 'email' => $user->email,
'subject' => '您在' . admin_setting('app_name', 'XBoard') . '的工单得到了回复', 'subject' => '您在' . admin_setting('app_name', 'Notification Service') . '的工单得到了回复',
'template_name' => 'notify', 'template_name' => 'notify',
'template_value' => [ 'template_value' => [
'name' => admin_setting('app_name', 'XBoard'), 'name' => admin_setting('app_name', 'Notification Service'),
'url' => admin_setting('app_url'), 'url' => admin_setting('app_url'),
'content' => "主题:{$ticket->subject}\r\n回复内容:{$ticketMessage->message}" 'content' => "主题:{$ticket->subject}\r\n回复内容:{$ticketMessage->message}"
] ]