发送邮件

This commit is contained in:
2025-03-14 17:10:14 +08:00
parent 624a2628d0
commit 5022d1f3d7
5 changed files with 178 additions and 3 deletions
+32 -1
View File
@@ -3,6 +3,7 @@
namespace app\controller;
use app\model\User;
use app\service\MailService;
use app\util\JwtUtil;
use app\util\Util;
use support\Redis;
@@ -13,7 +14,7 @@ class UserController
/**
* 不需要登录的方法
*/
protected $noNeedLogin = ['login'];
protected $noNeedLogin = ['login','sendCode'];
public function login(Request $request)
{
@@ -59,5 +60,35 @@ class UserController
return Util::success($result,trans('login_success'));
}
/**
* 发送邮箱验证码
* @param Request $request
* @return \support\Response
* @throws \Random\RandomException
*/
public function sendCode(Request $request)
{
// $email = $request->input('email');
$email = '1696136552@qq.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return json(['code' => 400, 'msg' => '邮箱格式错误']);
}
// 生成验证码
$code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
// 发送邮件
$mailService = new MailService();
if ($mailService->sendVerificationCode($email, $code)) {
// 存储验证码到 Redis
Redis::set("verification_code:{$email}", $code, 300);
return Util::success([],'验证码已发送');
}
return Util::fail([],'邮件发送失败');
}
}
+4
View File
@@ -58,7 +58,11 @@ class AuthMiddleware implements MiddlewareInterface
if ($isLogin && (!$token || !str_starts_with($token, 'Bearer '))) {
throw new BusinessException('请先登录', 302);
// throw new BusinessException('未提供 Token'.$isLogin, 401);
}elseif(!$isLogin){
return $handler($request);
}
$token = substr($token, 7);
try {
// 验证 Token 并获取用户ID
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace app\service;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use support\Log;
class MailService
{
protected $mailer;
public function __construct()
{
$this->mailer = new PHPMailer(true);
$this->configure();
}
protected function configure()
{
// SMTP 配置
$this->mailer->isSMTP();
$this->mailer->Host = 'smtp.qq.com';
$this->mailer->SMTPAuth = true;
$this->mailer->Username = '1696136552@qq.com'; // 替换为你的 Gmail
$this->mailer->Password = 'jhqkgjwzqqzgdcfd'; // 替换为应用专用密码
// $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 使用 TLS
$this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL 加密
// $this->mailer->Port = 587;
$this->mailer->Port = 465;
$this->mailer->CharSet = 'UTF-8';
}
/**
* 发送验证码邮件
* @param string $toEmail 收件邮箱
* @param string $code 验证码
* @return bool
*/
public function sendVerificationCode(string $toEmail, string $code): bool
{
try {
$this->mailer->setFrom('1696136552@qq.com', 'XinYouHe Code'); // 发件人
$this->mailer->addAddress($toEmail);
// 邮件内容
$this->mailer->isHTML(true);
$this->mailer->Subject = '您的验证码';
$this->mailer->Body = "您的CRM验证码是:<strong>{$code}</strong>,5分钟内有效。";
$this->mailer->send();
Log::info("邮件发送成功: {$toEmail}");
return true;
} catch (Exception $e) {
Log::error("邮件发送失败: " . $this->mailer->ErrorInfo);
return false;
}
}
}