request->post('email'); // 邮箱地址 $event = $this->request->post('event' ?? 'register'); // 验证码事件 if (!$email || !$event) { $this->fail(500, '请检查传参!'); } // 随机验证码 $code = mt_rand(1000, 9999); // 插入数据库 $row = Db::table('tb_email_captcha')->insert([ 'email' => $email, 'code' => $code, 'event' => $event, 'ip' => $this->request->ip(), 'createtime' => time(), ]); if (!$row) { $this->fail(500, '发送失败!请联系管理员处理!'); } $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.yeah.net'; // 设置 SMTP 服务器 $mail->SMTPAuth = true; // 启用 SMTP 认证 $mail->Username = 'danjiwanjia@yeah.net'; // 用户名 $mail->Password = 'UMt6A8pm2KY2unCM'; // 密码 $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // SMTP 协议类型 $mail->Port = 25; // SMTP 端口号 $mail->setFrom('danjiwanjia@yeah.net', '单机顽家'); $mail->addAddress($email); // 添加收件人 $mail->isHTML(true); // Set email format to HTML $mail->Subject = '单机顽家验证码'; $mail->Body = '您的验证码是:' . $code . ',请在5分钟内使用,答应我不要告诉别人哦!'; $mail->AltBody = '您的验证码是:' . $code; $mail->send(); $this->success('发送成功!', null); } // 内部调用 - 验证邮箱 public function verifyEmail($email, $code, $event = 'register') { if (!$email || !$event) { $this->fail(500, '请检查传参!'); } // 查询邮箱验证码 $query = Db::table('tb_email_captcha') ->where('email', $email) ->where('code', $code); $email = $query->find(); // 校验验证码状态 if (!$email) { // 验证码未找到或不正确 return false; } if ($email['times'] != 0 || time() - $email['createtime'] > 300) { // 验证码已经被使用或超过五分钟未使用 return false; } // 通过验证 将验证码标记为已使用 $query->update(['times' => 1]); return true; } // 用户验证邮箱 public function verifyUserEmail() { $code = $this->request->post('code');// 邮箱验证码 $user_id = $this->getUser()->user_id; // 验证用户 $user = Db::table('tb_user')->where('id', $user_id)->find(); if (!$user) { $this->fail(500, '无法找到用户信息!'); } // 验证用户邮箱 $verify = $this->verifyEmail($user['email'], $code, 'verify'); if (!$verify) { $this->fail(500, '验证码错误或已过期!'); } // 校验通过 更新用户邮箱已认证 Db::table('tb_user')->where('id', $user['id'])->update(['is_email_verified' => 1]); $this->success('success', null); } }