网易云邮箱发送验证码
1、进入网易云邮箱官网,点击设置进入POP3/SMTP/IMAP

2、开启服务

3、新增授权密码,并保存

4、pom.xml文件添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
5、添加application-mail.yml配置文件
spring:
mail:
host: smtp.163.com
username: xxxx@163.com
password: xxxxxxxxx
properties.mail.smtp.port: 465
nickname: 志小志
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
6、Controller层代码,前端传入收件人的邮箱
package com.qiu.controller;
import com.aliyuncs.utils.StringUtils;
import com.qiu.util.general.CommonResult;
import com.qiu.util.general.MyUtils;
import com.qiu.util.mail.IMailService;
import com.qiu.util.sms.AliYunSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@CrossOrigin
@RestController
public class UtilController {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private IMailService mailService;
@RequestMapping(value = "/allow/sendHtmlCode")
public CommonResult sendHtmlCode(String email) {
try {
String code = MyUtils.getCode(6);
Map<String, Object> data = new HashMap<>(2);
data.put("code", code);
data.put("year", Calendar.getInstance().get(Calendar.YEAR));
redisTemplate.opsForValue().set(email, code, 10, TimeUnit.MINUTES);
mailService.sendTemplateMail(email, "操作验证码", "mail", data);
return CommonResult.success("验证码已发送,网络有延迟请稍等~");
} catch (Exception e) {
return CommonResult.error("发送验证码时发生异常,请稍后重试!");
}
}
@RequestMapping(value = "/allow/sendHtmlRegister")
public CommonResult sendRegisterInfo(String email, String name, String password) {
try {
Map<String, Object> data = new HashMap<>(4);
data.put("account", email);
data.put("name", name);
data.put("password", password);
data.put("year", Calendar.getInstance().get(Calendar.YEAR));
mailService.sendTemplateMail(email, "注册成功", "register", data);
return CommonResult.success("注册信息发送成功");
} catch (Exception e) {
return CommonResult.error("注册信息发送失败");
}
}
@RequestMapping(value = "/allow/sendHtmlRole")
public CommonResult sendRoleInfo(String email, String userName, String roleInfo) {
try {
Map<String, Object> data = new HashMap<>(3);
data.put("userName", userName);
data.put("roleInfo", roleInfo);
data.put("year", Calendar.getInstance().get(Calendar.YEAR));
mailService.sendTemplateMail(email, "权限管理", "role", data);
return CommonResult.success("授权信息发送成功");
} catch (Exception e) {
return CommonResult.error("授权信息发送失败");
}
}
@RequestMapping(value = "/allow/sendHtmlResetPwd")
public CommonResult sendResetPwd(String email, String password) {
try {
Map<String, Object> data = new HashMap<>(2);
data.put("password", password);
data.put("year", Calendar.getInstance().get(Calendar.YEAR));
mailService.sendTemplateMail(email, "重置密码", "resetpwd", data);
return CommonResult.success("新密码信息发送成功");
} catch (Exception e) {
return CommonResult.error("新密码信息发送失败");
}
}
@RequestMapping(value = "/allow/checkCode")
public CommonResult checkCode(String key, String code) {
String codeK = redisTemplate.opsForValue().get(key);
if (codeK == null) {
return CommonResult.error("验证码不存在或已过期,请重新发送!");
}
if (codeK.equals(code)) {
redisTemplate.delete(key);
return CommonResult.success("验证码成功!", true);
} else {
return CommonResult.success("验证码错误!", false);
}
}
}
public class MyUtils {
public static String getCode(int length) {
String str = String.valueOf(System.currentTimeMillis());
return str.substring(str.length() - length);
}
private MyUtils() {
}
}
7、service层
package com.qiu.util.mail;
import java.util.Map;
public interface IMailService {
void sendSimpleMail(String to, String subject, String content);
void sendHtmlMail(String to, String subject, String content) throws Exception;
void sendAttachmentsMail(String to, String subject, String content, String filePath) throws Exception;
void sendTemplateMail(String to, String subject, String template, Map<String, Object> data) throws Exception;
}
8、service层的实现类impl
package com.qiu.util.mail.impl;
import com.qiu.util.mail.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;
@Slf4j
@Async
@Service
public class IMailServiceImpl implements IMailService {
@Autowired
private TemplateEngine templateEngine;
@Resource
private JavaMailSender mailSender;
@Value("${spring.mail.nickname}")
private String nickname;
@Value("${spring.mail.username}")
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(nickname + '<' + from + '>');
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
log.info("邮件已经发送");
}
@Override
public void sendHtmlMail(String to, String subject, String content) throws Exception {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper;
messageHelper = new MimeMessageHelper(message, true);
message.setFrom(nickname + '<' + from + '>');
messageHelper.setTo(to);
message.setSubject(subject);
messageHelper.setText(content, true);
mailSender.send(message);
log.info("邮件已经发送");
}
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws Exception {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(nickname + '<' + from + '>');
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
log.info("邮件已经发送");
}
@Async
@Override
public void sendTemplateMail(String to, String subject, String template, Map<String, Object> data) throws Exception {
System.out.println("to="+to);
System.out.println("subject="+subject);
System.out.println("template="+template);
System.out.println("data="+data);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(nickname + '<' + from + '>');
messageHelper.setTo(to);
messageHelper.setSubject(subject);
Context context = new Context();
context.setVariables(data);
String emailContent = templateEngine.process(template, context);
messageHelper.setText(emailContent, true);
mailSender.send(mimeMessage);
log.info("邮件已经发送");
}
}
9、mail.html 邮箱验证码模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="format-detection" content="telephone=no"/>
<title>乐购商城</title>
</head>
<body style="font-size: 13px">
<div class="main" style="padding-bottom:40px;background-color:#F1F1F1;">
<div class="header" style="padding: 10px 3%">
<h2 style="text-align:center;color: #FF6633">
乐购商城
</h2>
</div>
<div class="content" style="overflow: hidden;padding:15px 5% 70px 5%;margin:0 2%;background-color: #fff;box-shadow:0 4px 20px rgba(0,0,0,0.1);word-break: break-all;">
<p style="font-weight: bolder;margin-bottom: 5px;">尊敬的乐购商城用户,您好:</p>
<p style="margin-bottom: 30px;text-indent: 2em">请使用下面的验证码验证您的操作,验证码 10 分钟内有效: <a href="javascirpt:void(0)" onclick="return false;" th:text="${code}">602510</a></p>
</div>
</div>
<div class="footer" style="padding:7px 20px;background-color:#333;font-size:12px;color: #999;text-align: center">
<p content="telephone=no">Copyright © 2020 - <span th:text="${year}">2020</span>
</div>
</body>
</html>
10、resetpwd.html 重置密码模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="format-detection" content="telephone=no"/>
<title>乐购商城</title>
<style>
#cover{
border-radius: 6px;
outline:none;
height: 25px;
width: 122px;
cursor: pointer;
border:none;
background-color:#00DFDF;
}
</style>
<script>
function buttonClick(){
let password = document.getElementById("password");
let cover = document.getElementById("cover");
if(cover.innerText==='点击即可显示密码'){
cover.innerText='隐藏密码'
password.style.display='inline'
}else{
cover.innerText='点击即可显示密码'
password.style.display='none'
}
}
</script>
</head>
<body style="font-size: 13px">
<div class="main" style="padding-bottom:40px;background-color:#F1F1F1;">
<div class="header" style="padding: 10px 3%">
<h2 style="text-align:center;color: #FF6633">
乐购商城
</h2>
</div>
<div class="content" style="overflow: hidden;padding:15px 5% 70px 5%;margin:0 2%;background-color: #fff;box-shadow:0 4px 20px rgba(0,0,0,0.1);word-break: break-all;">
<p style="font-weight: bolder;margin-bottom: 5px;">尊敬的乐购商城用户,您好:</p>
<span style="text-indent: 2em;padding-left: 2em">密码重置成功,新密码为</span>
<p style="display: inline">
<span id="password" style="padding: 0 8px;font-weight: bolder; font-size: 15px;" th:text="${password}">123456</span>
</p>
</div>
</div>
<div class="footer" style="padding:7px 20px;background-color:#333;font-size:12px;color: #999;text-align: center">
<p content="telephone=no">Copyright © 2020 - <span th:text="${year}">2020</span>
</div>
</body>
</html>