大家在平时浏览网页的时候会经常看到这样的功能,在用户注册时需要发送手机验证码,或者邮箱验证码,那么这种功能是如何实现的呢?
验证码一般会有两种:
- 手机验证码:需要在第三方平台购买,要花钱的
- 邮箱验证码:免费的,任何人都可以用
本期文章分享SpringBoot整合发送邮件验证码,学会了,你也能用代码发邮件
前置工作
再此处以163邮箱为例,其他邮箱类似
开通POP3/SMTP服务
登录163邮箱,设置 -> POP3/STMP/IMAP
开启服务
验证后获取授权密码,只会显示一次哈,务必记住
功能实现
创建工程&倒入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
配置文件
server:
port: 2023
spring:
mail:
username: 你的邮箱
password: 你的授权码
host: smtp.163.com
邮件发送工具类
包含两个方法
- sendMail(): 通用的邮件发送方法
- buildCodeContent():构建模板邮件,模板文件在resources目录下
/**
* @Project: cxs-currency-sys-server
* @Author: cxs2014501@163.com
* @Create: 2023/2/8 13:37
* @Description:
**/
@Slf4j
@Component
public class SendMailUtil {
@Autowired
private JavaMailSenderImpl javaMailSender;
@Autowired
private MailConfig mailConfig;
/**
* 发送带附近的邮件信息
* @param to 收件人
* @param subject 主题
* @param content 内容
*/
public void sendMail(String to, String subject, String content) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject(subject);
helper.setText(content, true);
helper.setTo(to);
helper.setFrom(mailConfig.getUsername());
javaMailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
* 读取邮件模板
* 替换模板中的信息
* @param code 内容
* @return
*/
public String buildCodeContent(String code) {
//加载邮件html模板
Resource resource = new ClassPathResource("mailtemplate.ftl");
InputStream inputStream = null;
BufferedReader fileReader = null;
StringBuffer buffer = new StringBuffer();
String line = "";
try {
inputStream = resource.getStream();
fileReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = fileReader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
log.info("发送邮件读取模板失败{}", e);
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//替换html模板中的参数
return MessageFormat.format(buffer.toString(), "测试验证码", "全栈小白的手机号", mailConfig.getUsername(), code);
}
}
模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="email code">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<!--邮箱验证码模板-->
<body>
<div style="background-color:#ECECEC; padding: 35px;">
<table cellpadding="0" align="center"
style="width: 800px;height: 100%; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;">
<tbody>
<tr>
<th valign="middle"
style="height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: RGB(148,0,211); background-color: RGB(148,0,211); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;">
<font face="微软雅黑" size="5" style="color: rgb(255, 255, 255); ">{0}</font>
</th>
</tr>
<tr>
<td style="word-break:break-all">
<div style="padding:25px 35px 40px; background-color:#fff;opacity:0.8;">
<h2 style="margin: 5px 0px; ">
<font color="#333333" style="line-height: 20px; ">
<font style="line-height: 22px; " size="4">
尊敬的用户:</font>
</font>
</h2>
<!-- 中文 -->
<p>您好!感谢您使用小白博客,您的账号正在进行邮箱验证,验证码为:<font color="#ff8c00">{3}</font>,有效期3分钟,请尽快填写验证码完成验证!</p><br>
<div style="width:100%;margin:0 auto;">
<div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;">
<p>{0}团队</p>
<p>联系我们:{1}</p>
<p>官方邮箱:{2}</p>
<br>
<p>此为系统邮件,请勿回复<br>
Please do not reply to this system email
</p>
<!--<p>©***</p>-->
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
编写两个测试接口
- simple():测试简单邮件
- complex():测试模板邮件
/**
* @Project: spring-boot-mail-demo
* @Author: cxs2014501@163.com
* @Create: 2023/2/8 13:44
* @Description:
**/
@RestController
@RequestMapping("/mail")
public class MailController {
private static final String code = "888888";
@Autowired
private SendMailUtil sendMailUtil;
@GetMapping("/simple")
public String simple(@RequestParam("email") String email){
// 验证邮箱格式...
try {
sendMailUtil.sendMail(email, "简单邮件验证码测试", code);
return "OK";
} catch (Exception e) {
e.printStackTrace();
}
return "ERROR";
}
@GetMapping("/complex")
public String complex(@RequestParam("email") String email){
// 验证邮箱格式...
try {
sendMailUtil.sendMail(email, "复杂模板邮件验证码测试", sendMailUtil.buildCodeContent(code));
return "OK";
} catch (Exception e) {
e.printStackTrace();
}
return "ERROR";
}
}
测试
http://127.0.0.1:2023/mail/simple?email=要给谁发送的邮箱地址
http://127.0.0.1:2023/mail/complex?email=要给谁发送的邮箱地址