72 lines
2.4 KiB
Java
72 lines
2.4 KiB
Java
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();
|
||
}
|
||
}
|