使用springboot实现邮箱验证码功能

我这边使用的QQ邮箱

1、首先创建maven项目,配置pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>springbootdemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springbootdemo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>
		<!--邮件发送核心包-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
        </dependency>

		<!--mybatis分页插件-->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>4.1.6</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>src/main/java</directory>
					<includes>
						<include>**/*.xml</include>
					</includes>
			</resource>
		</resources>
	</build>

</project>

2、配置springboot,我这里使用的是properties方式

#配置Mybatis别名和扫描包
mybatis.type-aliases-package=com.demo.bean
mybatis.mapper-locations=classpath:mapper/*.xml

#数据库相关
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#配置日志
logging.level.root=info
logging.level.com.demo.mapper=debug

#配置视图前缀和后缀
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html

#邮件发送配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=你的邮箱
spring.mail.password=邮箱授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

#thymeleaf配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false

邮箱授权码可以按以下方法获取

打开QQ邮箱网页→设置→账户→POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务→开启POP3/SMTP服务,然后就能看到授权码了

3、编写mailService

      ${spring.mail.username}是在properties中配置的属性,这里有一个方法,第一个是发送普通邮件,第二个是发送带有附件的邮件

@Service("mailService")
public class MailService {
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public void sendSimpleMail(String to,String title,String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(title);
        message.setText(content);
        mailSender.send(message);
        logger.info("邮件发送成功");
    }

    public void sendAttachmentsMail(String to, String title, String cotent, List<File> fileList){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(cotent);
            String fileName = null;
            for (File file:fileList) {
                fileName = MimeUtility.encodeText(file.getName(), "GB2312", "B");
                helper.addAttachment(fileName, file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
        logger.info("邮件发送成功");
    }
}

4、编写controller

@Controller
public class MailController {
    @Autowired
    private MailService mailService;

    @RequestMapping("getCheckCode")
    @ResponseBody
    public String getCheckCode(String email){
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String message = "您的注册验证码为:"+checkCode;
        try {
            mailService.sendSimpleMail(email, "注册验证码", message);
        }catch (Exception e){
            return "";
        }
        return checkCode;
    }
}

5、编写页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <script src="layui/layui.js"></script>
</head>
<body style="width: 100%;height: 100%;">
    <div style="margin-top: 15%;">
        <div class="layui-main" style="width: 700px;">
            <h1 style="text-align: center">请输入注册信息</h1>
            <form class="layui-form layui-form-pane">
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱:</label>
                    <div class="layui-input-block">
                        <input id="email" type="email" name="username" class="layui-input" lay-verify="required"/>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码:</label>
                    <div class="layui-input-block">
                        <input id="password" type="password" name="password" class="layui-input" lay-verify="required"/>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱验证码:</label>
                    <div class="layui-input-block">
                        <input id="checkCode" type="text" name="checkCode" class="layui-input" lay-verify="required"/>
                        <button id="sendCheckCode" type="button" class="layui-btn layui-btn-normal">获取验证码</button>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="register">确认</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script>
        layui.use("form",function () {
            var form = layui.form;
            var $ = layui.$;
            
            form.on("submit(register)",function (data) {
                var inputCheckCode = $("#checkCode").val();
                if (inputCheckCode == checkCode){
                    $.ajax({
                        url:"/register",
                        type:"POST",
                        data:data.field,
                        async:false,
                        success:function (text) {
                            if ("ok" == text){
                                layer.alert("注册成功",function () {
                                    window.location.href = "index.html";
                                });
                            }else{
                                layer.alert("注册失败");
                            }
                        }
                    });
                } else{
                    layer.msg("验证码输入错误");
                }
                return false;
            });

            //验证码
            var checkCode = "";

            $("#sendCheckCode").click(function () {
                var email = $("#email").val();
                if (email == null || email == ""){
                    layer.msg("请输入邮箱!!!");
                    return;
                }
                var index = layer.open({
                    type:3,
                    content:"邮件发送中..."
                });

                $.ajax({
                    url:"/getCheckCode?email="+email,
                    type:"get",
                    success:function (text) {
                        if (text != null && text != ""){
                            layer.close(index);
                            layer.msg("已发送");
                            checkCode = text;
                            countDown();
                        } else{
                            layer.alert("获取失败,请重新获取")
                        }
                    }
                });
            });

            var maxTime = 60;
            function countDown(){
                if (maxTime == 0){
                    checkCode = "";
                    $("#sendCheckCode").removeClass("layui-btn-disabled");
                    $("#sendCheckCode").removeAttr("disabled")
                    $("#sendCheckCode").html("获取验证码");
                    maxTime = 60;
                }else{
                    $("#sendCheckCode").attr("disabled","disabled");
                    $("#sendCheckCode").addClass("layui-btn-disabled");
                    form.render();
                    $("#sendCheckCode").html(maxTime+"秒后重新获取");
                    maxTime--;
                    setTimeout(countDown,1000);
                }
            }

        });
    </script>
</body>
</html>

6、测试

邮件发送
邮件发送
发送成功
收到邮件
60s禁止重发

 

  • 9
    点赞
  • 81
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
要在Spring Boot中集成邮箱验证码功能,你可以按照以下步骤进行操作: 1. 在项目的pom.xml文件中添加mail模块的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 这样就可以使用Spring Boot提供的邮件功能了。\[1\] 2. 在配置文件(application.properties或application.yml)中填写相关的邮箱配置,例如使用163邮箱: ```properties # Mail spring.mail.host=smtp.163.com spring.mail.username=your-email@163.com spring.mail.password=your-password spring.mail.default-encoding=UTF-8 mail.from=your-email@163.com ``` 其中,`spring.mail.host`是SMTP服务器地址,`spring.mail.username`和`mail.from`是你的邮箱地址,`spring.mail.password`是你的邮箱授权码(不是邮箱密码)。你需要在相关邮箱设置中开启SMTP服务,并获取授权码。\[2\]\[3\] 3. 在你的代码中使用JavaMailSender发送邮件,可以通过注入`JavaMailSender`对象来实现: ```java @Autowired private JavaMailSender javaMailSender; public void sendVerificationCode(String email, String code) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(email); message.setSubject("验证码"); message.setText("您的验证码是:" + code); javaMailSender.send(message); } ``` 以上代码示例中,`sendVerificationCode`方法用于发送验证码邮件,其中`email`是收件人邮箱地址,`code`是验证码内容。你可以根据实际需求自定义邮件的主题和内容。 这样,你就可以在Spring Boot中集成邮箱验证码功能了。记得替换相关配置为你自己的邮箱信息。 #### 引用[.reference_title] - *1* *2* *3* [Spring Boot 整合163或者qq邮箱发送验证码](https://blog.csdn.net/hghjgkjn/article/details/125952509)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值