邮件登录之自定义邮件
邮件登录之自定义邮件
上一篇我们分享了如何实现联系qq邮箱来实现验证码登录,这里接上回的自定义邮件功能。
一、依赖
添加模板引擎依赖:
<!-- Thymeleaf 模板引擎 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>二、工具类的改造
@Component
public class MailUtil {@Autowiredprivate JavaMailSender mailSender;@Autowiredprivate TemplateEngine templateEngine;@Value("${spring.mail.username}")private String from;public void sendVerificationMail(String to, String code) {try {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");helper.setFrom(new InternetAddress(from, "验证中心", "UTF-8"));helper.setTo(to);helper.setSubject("登录验证码");// 填充模板变量Context context = new Context();context.setVariable("code", code);String html = templateEngine.process("mail", context);helper.setText(html, true);// 添加嵌入资源(logo + 背景)helper.addInline("logo", new ClassPathResource("templates/images/logo.png"));mailSender.send(message);} catch (IOException e) {System.err.println("资源文件路径错误!");e.printStackTrace();} catch (Exception e) {System.err.println(" 邮件发送失败!");e.printStackTrace();}}
}三、控制器的改造
@GetMapping("/sendCode")
public String sendCode(@RequestParam String email) {String key = "login:code:" + email;String cooldownKey = "login:cooldown:" + email;// 生成验证码String code = String.valueOf(100000 + new Random().nextInt(900000));if (Boolean.TRUE.equals(redisTemplate.hasKey(cooldownKey))) {return "发送过于频繁,请稍后再试。";}// 检查 Redis 中是否已有未过期验证码if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {return "验证码未过期,请检查您的邮箱。";}redisTemplate.opsForValue().set(cooldownKey, "1", 60, TimeUnit.SECONDS);try {// 发送邮件mailUtil.sendVerificationMail(email, code);// 邮件发送成功后再写入 RedisredisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);} catch (Exception e) {e.printStackTrace();return "邮件发送失败,请稍后重试。";}return "验证码已发送到 " + email;
}四、创建html文件
在html标签中:
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
创建src/main/resources/templates/mail.html 文件
Mail 文件直接写 html的样式 资源路径这样实现:
<img src="cid:logo" class="logo" alt="CY-Fang Logo">
验证码这样实现:
<p class="code" th:text="${code}">123456</p>
需要注意的是邮箱对一些html的某些功能支持很少,也就是说在浏览器中的样式可能会在某些邮箱中无法显示,,,,然后要注意下响应式布局。。
如此,再次发送验证码时,邮件就会显示为我们想要的样式。。
