validate([ 'email' => 'required|email' ]); $email = $request->input('email'); $user = $request->user(); // 1. 检查总控制开关 if (SysParam::where('alias', 'smtp_enabled')->value('body') !== '1') { return response()->json([ 'status' => 'error', 'message' => '抱歉,当前系统未开启外部邮件发信服务,请联系管理员。' ], 403); } // 2. 检查是否有频率限制(同一用户或同一邮箱,60秒只允许发1次) $throttleKey = 'email_throttle_' . $user->id; if (Cache::has($throttleKey)) { $ttl = Cache::ttl($throttleKey); return response()->json([ 'status' => 'error', 'message' => "发送过于频繁,请等待 {$ttl} 秒后再试。" ], 429); } // 3. 生成 6 位随机验证码并缓存,有效期 5 分钟 $code = mt_rand(100000, 999999); $codeKey = 'email_verify_code_' . $user->id . '_' . $email; Cache::put($codeKey, $code, now()->addMinutes(5)); // 设置频率锁,过期时间 60 秒 Cache::put($throttleKey, true, now()->addSeconds(60)); // 4. 执行发信动作 try { Mail::raw("【飘落的流星】聊天室\n\n您正在试图绑定或修改您的验证邮箱。\n该操作的验证码为:{$code}\n打死不要告诉其他人哦!验证码5分钟内有效。", function ($msg) use ($email) { $msg->to($email)->subject('飘落流星聊天室 - 绑定邮箱验证码'); }); return response()->json([ 'status' => 'success', 'message' => '验证码已发送,请注意查收邮件。' ]); } catch (\Throwable $e) { // 如果发信失败,主动接触频率限制锁方便用户下一次立重试 Cache::forget($throttleKey); return response()->json([ 'status' => 'error', 'message' => '邮件系统发送异常,请稍后再试: ' . $e->getMessage() ], 500); } } }