写在前面
这里主要讲解大致思路
详细代码(目前部分功能还在开发完善中) 请见这里
如果个人用户还是想白嫖短信服务的话,可以看看我的这篇博客
一、开启 POP3/SMTP服务 获得的授权码
这里以qq邮箱为例
点击 设置
点击 账户
开启相关服务
复制授权码
二、导入相关依赖并配置application.yml
pom.xml
<!-- 邮件服务 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Thymeleaf 模版,用于发送模版邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.yml
# 邮箱配置
mail:
host: smtp.qq.com # 发送邮件的服务器地址
username: 填写自己的qq邮箱账号 # 开启 IMAP/SMTP服务 的qq邮箱的账号
password: 填写自己的授权码 # 开启 IMAP/SMTP服务 获得的授权码,而不是qq邮箱的登录密码
default-encoding: UTF-8
三、编写对应的接口
Controller
/**
* 发送邮箱验证码
*
* @param user
* @return
*/
@PostMapping("/sendMsg")
public R<String> sendMsg(@RequestBody User user, HttpSession session) {
// 获取邮箱账号
String phone = user.getPhone();
String subject = "瑞吉餐购登录验证码";
if (StringUtils.isNotEmpty(phone)) {
String code = ValidateCodeUtils.generateValidateCode(4).toString();
String context = "欢迎使用瑞吉餐购,登录验证码为: " + code + ",五分钟内有效,请妥善保管!";
log.info("code={}", code);
// 真正地发送邮箱验证码
userService.sendMsg(phone, subject, context);
// 将随机生成的验证码保存到session中
// session.setAttribute(phone, code);
// 验证码由保存到session 优化为 缓存到Redis中,并且设置验证码的有效时间为 5分钟
redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
return R.success("验证码发送成功,请及时查看!");
}
return R.error("验证码发送失败,请重新输入!");
}
Service
/**
* 发送邮箱
* @param to
* @param subject
* @param context
*/
void sendMsg(String to,String subject,String context);
ServiceImpl
@Value("${spring.mail.username}")
private String from; // 邮件发送人
@Autowired
private JavaMailSender mailSender;
@Override
public void sendMsg(String to, String subject, String context) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(from);
mailMessage.setTo(to);
mailMessage.setSubject(subject);
mailMessage.setText(context);
// 真正的发送邮件操作,从 from到 to
mailSender.send(mailMessage);
}