|
|
|
@ -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 "邮件发送失败";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|