邮件服务控制器/邮件服务接口

master
wjy 2 months ago
parent 5ede697ed0
commit 61cc373a33

@ -0,0 +1,52 @@
package com.example.api.controller;
import com.example.api.utils.RandomUtil; // 导入自定义工具类,用于生成随机数或随机字符串
import org.springframework.beans.factory.annotation.Value; // 导入@Value注解用于注入配置文件中的值
import org.springframework.mail.MailException; // 导入MailException用于捕获邮件发送过程中的异常
import org.springframework.mail.SimpleMailMessage; // 导入SimpleMailMessage用于构建简单的邮件消息
import org.springframework.mail.javamail.JavaMailSender; // 导入JavaMailSender用于发送邮件
import org.springframework.web.bind.annotation.GetMapping; // 导入@GetMapping注解用于处理GET请求
import org.springframework.web.bind.annotation.RequestMapping; // 导入@RequestMapping注解用于定义请求的映射路径
import org.springframework.web.bind.annotation.RestController; // 导入@RestController注解标识该类为RESTful控制器
import javax.annotation.Resource; // 导入@Resource注解用于依赖注入
// 定义RestController注解标识该类为一个RESTful控制器
@RestController
// 定义RequestMapping注解设置基础URL路径为"/api/email"所有方法的URL都将在此基础上构建
@RequestMapping("/api/email")
public class EmailController {
// 使用@Resource注解自动注入JavaMailSender用于发送邮件
@Resource
private JavaMailSender mailSender;
// 使用@Value注解注入配置文件中的邮件用户名作为发件人地址
@Value("${spring.mail.username}")
private String from;
// 处理GET请求用于发送邮件
@GetMapping("/send")
public String send() {
SimpleMailMessage message = new SimpleMailMessage();
// 设置发件人地址
message.setFrom(from);
// 设置收件人地址
message.setTo("1402014577@qq.com");
// 设置邮件主题
message.setSubject("验证码");
// 设置邮件内容,包括一个随机生成的验证码
message.setText("你的验证码为: " + RandomUtil.next() + " 十五分钟内有效");
try {
// 发送邮件
mailSender.send(message);
// 如果发送成功,返回成功消息
return "发送普通邮件成功";
} catch (MailException e) {
// 如果发送失败,打印堆栈跟踪并返回失败消息
e.printStackTrace();
return "邮件发送失败";
}
}
}

@ -0,0 +1,26 @@
package com.example.api.service;
import org.springframework.mail.MailException; // 导入Spring邮件异常类用于处理邮件发送过程中的异常
/**
*
*/
public interface EmailService {
/**
*
* @param email
* @return truefalse
* @throws MailException MailException
*/
boolean sendVerificationCode(String email) throws MailException;
/**
*
* @param email
* @param code
* @return truefalse
*/
boolean checkVerificationCode(String email, String code);
}
Loading…
Cancel
Save