SpringBoot集成邮箱验证码功能(注册/改密)

准备工作

开启SMTP服务

前往你的邮箱网站,以网易邮箱为例,打开网易邮箱地址,登录你的邮箱,进入邮箱管理后台界面。点击"设置"》》"POP3/SMTP/IMAP"后,点击开启SMTP服务即可。

技术实现

Spring Boot 发送邮件验证码的功能,主要用到了spring-boot-starter-mail工具包实现邮件的发送功能,利用junit-vintage-engine工具包实现了html邮件模板功能,利用easy-captcha工具包生成随机验证码 的功能!

引入依赖

复制代码
     <!--引入mail依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
         <!--mail模板-->
         <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
          <!--验证码-->
        <dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>

相关配置

然后再spring的配置文件中,设置mail相关配置:

复制代码
spring:
  mail:
    host: smtp.yeah.com
    username: 你的邮箱
    password: 邮箱授权码
    default-encoding: UTF-8
    protocol: smtp
    properties:
      mail:
        smtp:
           auth: true # 启用SMTP认证
           starttls:
              enabled: true # 启用SMTP认证
              required: true # 必须采用加密链接

代码实现

创建一个MailService类,实现邮件发送的功能,代码如下:

html 复制代码
package com.ruoyi.framework.web.service;

import com.ruoyi.common.utils.DateUtils;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Objects;


/**
 * 邮箱验证码
 *
 * @author lsyong
 */
@Component
public class MailService {

	private static final StringTemplateGroup templateGroup;

	private static final String SITE_NAME = "XXXXXXX";

	static{
		String classpath = Objects.requireNonNull(MailService.class.getClassLoader().getResource("")).getPath();
		templateGroup = new StringTemplateGroup("mailTemplates");
	}

	public static String IMG_BASE_URL;
	public static String ACTIVATE_CONTEXT="http:";
	public static String RESET_PWD_CONTEXT;

	@Value("${spring.mail.username}")
	private String username;
    @Resource
    private JavaMailSender mailSender;


    private void sendMail(String to, String subject, String body) {
    	MimeMessage mail = mailSender.createMimeMessage();
    	try {
    		MimeMessageHelper helper = new MimeMessageHelper(mail, true, "utf-8");
			helper.setFrom(new InternetAddress(MimeUtility.encodeText(SITE_NAME)+"<"+username+">").toString());
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(body, true);
			helper.setSentDate(DateUtils.getNowDate());
			mailSender.send(mail);
		} catch (MessagingException|UnsupportedEncodingException e) {

		}
	}

    /**
     * 账号激活
     * @param to,key
     */
    public void sendAccountActivationEmail(String to, String key){
    	StringTemplate activation_temp = templateGroup.getInstanceOf("activation");
    	activation_temp.setAttribute("img_base_url", IMG_BASE_URL);
    	activation_temp.setAttribute("email", to);
    	activation_temp.setAttribute("href", ACTIVATE_CONTEXT+key+"?email="+to);
    	activation_temp.setAttribute("link", ACTIVATE_CONTEXT+key+"?email="+to);
    	sendMail(to, SITE_NAME+"账户激活", activation_temp.toString());
    }
    /**
     * 发送验证码
     * @param to,code
     */
	@Async
	public void sendEmailCode(String to, String code){
		StringTemplate activation_temp = templateGroup.getInstanceOf("verificationCode");
		activation_temp.setAttribute("img_base_url", IMG_BASE_URL);
		activation_temp.setAttribute("email", to);
		activation_temp.setAttribute("code", code);
		sendMail(to, SITE_NAME+"邮箱验证码", activation_temp.toString());
	}

    /**
     * 修改密码
     * @param to,key
     */
    public void sendResetPwdEmail(String to, String key){
    	StringTemplate activation_temp = templateGroup.getInstanceOf("resetpwd");
    	activation_temp.setAttribute("img_base_url", IMG_BASE_URL);
    	activation_temp.setAttribute("href", RESET_PWD_CONTEXT+"?key="+key+"&email="+to);
    	activation_temp.setAttribute("link", RESET_PWD_CONTEXT+"?key="+key+"&email="+to);
    	sendMail(to, SITE_NAME+"账户密码重置", activation_temp.toString());
    }
}

新建verificationCode.st 代码如下:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>XXXXXX邮箱验证码</title>
	<style type="text/css">
	body{
		font-family: '微软雅黑','Helvetica Neue',sans-serif;
	}
	.container{
		max-width: 600px;
		margin: 0 auto;
	}
	.segment{
		background: #fff;
    	border: 1px solid #e9e9e9;
    	border-radius: 3px;
    	padding: 20px;
	}
	.header{
		margin: 10px 0 30px 0;
		font-weight: 400;
    	font-size: 20px;
	}
	.logo{
	    margin: 0 auto;
	    text-align: center;
	    margin-bottom: 28px;
	}
	.logo img{
		width: 28px;
		height: auto;
	}
	</style>
</head>
<body>
	<div class="container">
		<div class="segment">
			<div class="logo">
				<img src="$img_base_url$logo_for_mail.png">
			</div>
			<div class="content">
				<div class="header">
					$email$
				</div>
				<p>欢迎加入XXXXXXX</p>
				<div>
					<p>您的验证码是:</p>
					<b>$code$</b>
				</div>
				<p>
					验证码有效时间为XX分钟,如果验证码失效,请重新点击发送验证码
				</p>
			</div>
		</div>
	</div>
</body>
</html>
相关推荐
爬山算法14 分钟前
Hibernate(87)如何在安全测试中使用Hibernate?
java·后端·hibernate
WeiXiao_Hyy32 分钟前
成为 Top 1% 的工程师
java·开发语言·javascript·经验分享·后端
玄同76533 分钟前
SQLite + LLM:大模型应用落地的轻量级数据存储方案
jvm·数据库·人工智能·python·语言模型·sqlite·知识图谱
吾日三省吾码34 分钟前
别只会“加索引”了!这 3 个 PostgreSQL 反常识优化,能把性能和成本一起打下来
数据库·postgresql
chian-ocean36 分钟前
百万级图文检索实战:`ops-transformer` + 向量数据库构建语义搜索引擎
数据库·搜索引擎·transformer
苏渡苇38 分钟前
优雅应对异常,从“try-catch堆砌”到“设计驱动”
java·后端·设计模式·学习方法·责任链模式
long3161 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
小Tomkk1 小时前
数据库 变更和版本控制管理工具 --Bytebase 安装部署(linux 安装篇)
linux·运维·数据库·ci/cd·bytebase
独断万古他化1 小时前
【SSM开发实战:博客系统】(三)核心业务功能开发与安全加密实现
spring boot·spring·mybatis·博客系统·加密
rannn_1111 小时前
【苍穹外卖|Day4】套餐页面开发(新增套餐、分页查询、删除套餐、修改套餐、起售停售)
java·spring boot·后端·学习