@RestController
@RequestMapping("email")
public class EmailController {
// 引入邮件接口
@Autowired
private JavaMailSender mailSender;
// 获得发件人信息
@Value("${spring.mail.username}")
private String from;
@RequestMapping("sendEmail")
public R commonEmail(ToEmail toEmail) {
// 创建邮件消息
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(toEmail.getTos());
message.setSubject("您本次的验证码是");
int verCode = ValidateCodeUtils.generateValidateCode(4);
message.setText("尊敬的xxx,您好:\n"
+ "\n本次请求的邮件验证码为:" + verCode + ",本验证码 5 分钟内效,请及时输入。(请勿泄露此验证码)\n"
+ "\n如非本人操作,请忽略该邮件。\n(这是一封通过自动发送的邮件,请不要直接回复)");
mailSender.send(message);
return R.ok("发送成功");
}
}
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ToEmail implements Serializable {
// 邮件接收方
private String[] tos;
// 邮件主题
private String subject;
// 邮件内容
private String content;
}
需要添加maven依赖
<!-- 邮箱验证码依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
需要配置yml文件
spring:
#邮箱验证码配置
mail:
#smtp服务主机 qq邮箱则为smtp.qq.com;163邮箱是smtp.163.com
host: smtp.qq.com
#服务协议
protocol: smtp
# 编码集
default-encoding: UTF-8
#发送邮件的账户
username: xxxxxxxxxxxxxx@qq.com
#授权码
password: xxxxxxxxxxxxxx
test-connection: true
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true