company-backend/src/main/java/com/example/mailservice/controller/MailController.java

72 lines
2.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.example.mailservice.controller;
import com.example.mailservice.dto.ApiResponse;
import com.example.mailservice.dto.MailRequest;
import com.example.mailservice.service.MailLimitService;
import com.example.mailservice.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* 邮件发送控制器
*/
@RestController
@RequestMapping("/api/mail")
public class MailController {
@Autowired
private MailService mailService;
@Autowired
private MailLimitService mailLimitService;
/**
* 发送邮件接口
*/
@PostMapping("/send")
public ApiResponse sendMail(@Validated @RequestBody MailRequest mailRequest, HttpServletRequest request) {
// 获取客户端IP地址
String ipAddress = getClientIpAddress(request);
// 检查是否达到发送限制
if (!mailLimitService.canSendMail(ipAddress)) {
return ApiResponse.fail(403, "您的IP今日发送邮件已达上限请明天再试");
}
// 发送邮件
boolean sendSuccess = mailService.sendSimpleMail(
mailRequest.getName(),
mailRequest.getEmail(),
mailRequest.getSubject(),
mailRequest.getMessage()
);
if (sendSuccess) {
// 增加发送计数
long count = mailLimitService.incrementSendCount(ipAddress);
int remaining = mailLimitService.getRemainingCount(ipAddress);
return ApiResponse.success("邮件发送成功,今日剩余发送次数: " + remaining);
} else {
return ApiResponse.fail(500, "邮件发送失败,请稍后重试");
}
}
/**
* 获取客户端IP地址
*/
private String getClientIpAddress(HttpServletRequest request) {
String xForwardedForHeader = request.getHeader("X-Forwarded-For");
if (xForwardedForHeader != null) {
// X-Forwarded-For: client, proxy1, proxy2
return xForwardedForHeader.split(",")[0].trim();
}
return request.getRemoteAddr();
}
}