java案例----用户注册--发送邮件并激活/发送邮件验证码

java案例----用户注册—发送邮件并激活/发送邮件验证码

一、前期准备

1、准备两个邮箱账号(一个发邮件,一个收邮件)

1.1)登录需要发送邮件的QQ邮箱,找到设置项
1.2)然后在账户栏下,找到(POP3/SMTP)服务协议

在这里插入图片描述

1.3)生成授权码

下拉找到 POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 打开 POP3/SMTP服务,并记住授权码,后面发送邮件时会用到授权码
在这里插入图片描述

二、项目

1、准备用户数据表

CREATE TABLE `user` (
  `userid` int(20) NOT NULL AUTO_INCREMENT COMMENT '用户编号',
  `name` varchar(16) DEFAULT NULL COMMENT '姓名',
  `password` varchar(16) DEFAULT '' COMMENT '密码',
  `sex` varchar(12) DEFAULT NULL COMMENT '性别',
  `idno` varchar(18) DEFAULT NULL COMMENT '身份证号码',
  `tel` int(11) DEFAULT NULL COMMENT '手机号码',
  `user_verification_code` int(6) DEFAULT NULL COMMENT '验证码',
  `user_activation_code` varchar(255) DEFAULT NULL COMMENT '激活码',
  `eml` varchar(255) DEFAULT '' COMMENT '邮箱',
  `vipid` int(1) DEFAULT 0 COMMENT '会员等级',
  `permissionid` int(1) DEFAULT 0 COMMENT '权限等级',
  `registerdata` datetime DEFAULT NULL COMMENT '注册日期',
  `status` tinyint(1) DEFAULT NULL COMMENT '状态:0 未激活 1激活',
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=1035 DEFAULT CHARSET=utf8

在这里插入图片描述

2、idea 创建项目

2.1)在项目的pom表中导入邮件jar包
		<!--引入邮件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

为了使项目能够跑通测试,以下是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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<!--
      定位: SpringBoot主要的作用整合SSM,使得框架的使用更加简化
      原则: "开箱即用"
      parent主要的作用:
             1.SpringBoot在内部兼容了当下几乎所有的第三方框架
             2.SpringBoot官网已经将所有兼容的版本进行了定义
              (几乎解决了版本冲突问题)以后几乎不写版本号
      概括: parent标签中管理其他的项目版本信息.
  -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<!--坐标-->
	<groupId>com.demo</groupId>
	<artifactId>yuyue</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>yuyue</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<!--跳过测试类打包-->
		<skipTests>true</skipTests>
	</properties>

	<!--原则: 按需导入  -->
	<dependencies>
		<dependency>
			<!--springboot启动项(器)在包的内部SpringBoot
		   已经完成了项目的"整合"(配置) 用户拿来就用
		   web导入SpringMVC
		   -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</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-devtools</artifactId>
			<optional>true</optional>
		</dependency>

		<!--添加lombok依赖-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

		<!--引入数据库驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!--springBoot数据库连接  -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<!--导入MP包之后,删除原有的Mybatis的包 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.3</version>
		</dependency>

		<!--引入邮件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
	</dependencies>

	<!--SpringBoot项目与Maven整合的一个插件
	   可以通过插件 执行项目打包/测试/文档生成等操作
	   注意事项: 该插件不能省略
	   项目发布时: java -jar xxxx.jar  报错:没有主清单信息!!!!
   -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<fork>true</fork><!--热部署必须添加这个配置-->
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>
2.2)创建user类—用户类
package com.demo.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.sql.Timestamp;

@Data							//lombok---自动创建get、set等方法
@NoArgsConstructor				//lombok---无参构造
@AllArgsConstructor				//lombok---全参构造
@Accessors(chain = true)		//开启链式编程
@TableName("user")    			//关联数据表--user表的名字
public class User {
	//主键自增
	@TableId(type= IdType.AUTO)
	private Integer userid;         		//登录账号
	private String name;            		//姓名
	private String password;        		//密码
	private String repassword;      		//确认密码
	private String sex;             		//性别
	private String idno;            		//身份证号码
	private Integer userVerificationCode; 	//验证码
	private Integer userActivationCode; 	//激活码
	private String eml;             		//邮箱
	private String tel;             		//联系电话
	private Integer vipid;          		//vip标志id
	private Integer permissionid;   		//权限标志id
	private boolean status;					//状态:0 未激活 1激活
	//日期出参格式化
	@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
	private Timestamp registerdata;      	//注册时间
	
	
	@TableField(exist = false)         		//不是数据表格中固有的属性
	private String vipname;          		//vip标志名称
	
	@TableField(exist = false)         		//不是数据表格中固有的属性
	private String permissionname; 			//权限标志名称
}

2.3)创建配置文件
server:
  port: 8090

spring:
  #连接数据数据库
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/yuyue?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root
    #如果数据库密码以数字0开头 则必须使用""号包裹
    #password: "01234"
  
  #连接发送者邮箱
  mail:
    host: smtp.qq.com #这个是QQ邮箱的,发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com,可以百度
    username: Xxx@qq.com #qq邮箱	
    password: 			 #qq邮箱授权码
    protocol: smtp #发送邮件协议
    properties.mail.smtp.auth: true   #设置是否需要认证,如果为true,那么用户名和密码就必须的,
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true #开启SSL
    default-encoding: utf-8


#SpringBoot整合MP配置
mybatis-plus:
  #定义别名包: 实现对象映射
  type-aliases-package: com.demo.pojo
  #加载映射文件一个接口对应一个映射文件
  mapper-locations: classpath:/mybatis/*.xml
  #开启驼峰映射
  configuration:
    map-underscore-to-camel-case: true


#不打印日志
debug: false

#Mapper接口执行 打印Sql日志
logging:
  level:
    com.jt.mapper: debug

2.3.1)邮件的配置文件,application.yml写法
spring:
  mail:
    host: smtp.qq.com #发送邮件服务器
    username: xx@qq.com #发送者邮箱
    password: xxxxxxxx #发送者邮箱授权码
    protocol: smtp #发送邮件协议
    properties.mail.smtp.auth: true #开启认证
    properties.mail.smtp.port: 994 #设置端口465或者994
    properties.mail.display.sendmail: aaa #可以任意
    properties.mail.display.sendname: bbb #可以任意
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true #开启SSL
    default-encoding: utf-8
    #from: xx@qq.com  #发送者邮箱
2.3.2)邮件的配置文件,application.properties写法
spring.mail.host=smtp.qq.com  //这个是QQ邮箱的  其他邮箱请另行百度
spring.mail.username=用户名  //发送方的邮箱
spring.mail.password=密码  //对于qq邮箱而言 密码指的就是发送方的授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true  
spring.mail.properties.mail.smtp.starttls.enable=true //开启SSL
spring.mail.properties.mail.smtp.starttls.required=true  
2.4)创建EmailController类
package com.demo.controller;

import com.demo.pojo.User;
import com.demo.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController//接受请求
@CrossOrigin //解决跨域
@RequestMapping("/email") //访问路径
public class EmailController{

    //注入对象
    @Autowired
    private EmailService emailService;

    @PostMapping ("/sendEmail")
    public String sendEmail(User user){
        System.out.println("发送邮件。。。。");
        return emailService.sendEmail(user);
    }

    @PostMapping ("/verificationEmail")
    public String verificationEmail(User user){
        System.out.println("验证-邮箱发送的验证码。。。。");
        return emailService.verificationEmail(user);
    }
}
2.5)创建EmailService 类
package com.demo.service;

import com.demo.pojo.User;

public interface EmailService {
    //发送验证码
    String sendEmail(User user);
}

2.6)创建EmailServiceImpl 类
package com.demo.service;

import com.demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
@Service
public class EmailServiceImpl implements EmailService {

    //定义验证码
    private  Integer userVerificationCode = null;

    @Autowired
    JavaMailSender jms;

    //读取配置文件邮箱账号参数
    @Value("${spring.mail.username}")
    private String sender;

    //发送验证码
    @Override
    public String sendEmail(User user) {
        //随机数用作验证
        Integer userVerificationCode = new Random().nextInt(999999);
        try {
            //建立邮件消息
            SimpleMailMessage mainMessage = new SimpleMailMessage();

            //发送者
            mainMessage.setFrom(sender);

            //接收者
            mainMessage.setTo(user.getEml());

            //发送的标题
            mainMessage.setSubject("邮箱验证");

            //发送的内容
            String msg = "您好!" + user.getEml() + ",您正在使用邮箱验证,验证码:" + userVerificationCode + "。";
            mainMessage.setText(msg);

            //发送邮件
            jms.send(mainMessage);

            //下面是加入缓存,以便于进行邮箱验证
            this.userVerificationCode = userVerificationCode;

        } catch (Exception e) {
            return ("发送邮件失败,请核对邮箱账号");
        }
        return "验证码已经发送您的邮箱,请前去邮箱查看,验证码是:" + userVerificationCode ;
    }

    @Override
    public String verificationEmail(User user) {
        if (this.userVerificationCode.equals(user.getUserVerificationCode())){
            return "验证成功";
        }
        return "验证失败";
    }
}

3、准备网页

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>邮箱验证测试</title>
		<script src="../js/jquery-3.6.0.min.js"></script>
		<script src="../js/axios.js"></script>
		<script>
			function register(){
				axios.post("http://localhost:8090/fkxinli/register", $("#f1").serialize())
							.then(function(result){
							console.log(result.data)
				})
			}
			function register1(){
				$.ajax({ //发起Ajax请求数据
					type: "POST", //POST隐藏请求自带的数据,get显示请求自带的数据
					url: "http://localhost:8080/fkxinli/register", //要使用的请求路径
					//contentType: "application/json;charset=utf-8",
					data:$("#f1").serialize(),
					success: function(data) { //成功时的方案
						document.write(data);
					},
					error: function(data) {
						//alert("返回失败");
						//console.log("注册失败");
						
					}
				})
			}
			function sendEmail(){
				$.ajax({ //发起Ajax请求数据
					type: "POST", //POST隐藏请求自带的数据,get显示请求自带的数据
					url: "http://localhost:8090/email/sendEmail", //要使用的请求路径
					//contentType: "application/json;charset=utf-8",
					data:$("#f1").serialize(),
					success: function(data) { //成功时的方案
						alert(data);
					},
					error: function(data) {
						//alert("返回失败");
						//console.log("注册失败");
					}
				})
			}
			function verificationEmail(){
				$.ajax({ //发起Ajax请求数据
					type: "POST", //POST隐藏请求自带的数据,get显示请求自带的数据
					url: "http://localhost:8090/email/verificationEmail", //要使用的请求路径
					//contentType: "application/json;charset=utf-8",
					data:$("#f1").serialize(),
					success: function(data) { //成功时的方案
						alert(data);
					},
					error: function(data) {
						//alert("返回失败");
						//console.log("注册失败");
					}
				})
			}
			<!--返回首页-->
			function returnfrontpage(){
				window.open("../1-homepage/frontpage.html")
			}
		</script>
	</head>
	<body>
		<h1 align="center">邮箱验证测试</h1>
		<form  id="f1">
			<table align="center">
				<tr>
					<td>电子邮箱:</td>
					<td>
						<input type="email" name="eml" placeholder="请输入电子邮箱"/>
						<input type="button" value="发送验证码" onclick="sendEmail()" />
					</td>
				</tr>
				
				<tr>
					<td>邮箱验证码:</td>
					<td>
						<input type="text" name="userVerificationCode" placeholder="请输入邮箱验证码"/>
						<input type="button" value="验证--邮箱发送的验证码" onclick="verificationEmail()" />
					</td>
				</tr>
				
			</table>
			
		</form>
	</body>
</html>

4、测试

后端代码,写的比较简单,仅仅测试邮箱是否能够发送验证码
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 8
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
public synchronized String nextId() { long timestamp = timeGen(); //获取当前毫秒数 //如果服务器时间有问题(时钟后退) 报错。 if (timestamp < lastTimestamp) { throw new RuntimeException(String.format( "Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果上次生成时间和当前时间相同,在同一毫秒内 if (lastTimestamp == timestamp) { //sequence自增,因为sequence只有12bit,所以和sequenceMask相与一下,去掉高位 sequence = (sequence + 1) & sequenceMask; //判断是否溢出,也就是每毫秒内超过4095,当为4096时,与sequenceMask相与,sequence就等于0 if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); //自旋等待到下一毫秒 } } else { sequence = 0L; //如果和上次生成时间不同,重置sequence,就是下一毫秒开始,sequence计数重新从0开始累加 } lastTimestamp = timestamp; long suffix = (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; String datePrefix = DateFormatUtils.format(timestamp, "yyyyMMddHHMMssSSS"); return datePrefix + suffix; } protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } protected long timeGen() { return System.currentTimeMillis(); } private byte getLastIP(){ byte lastip = 0; try{ InetAddress ip = InetAddress.getLocalHost(); byte[] ipByte = ip.getAddress(); lastip = ipByte[ipByte.length - 1]; } catch (UnknownHostException e) { e.printStackTrace(); } return lastip; }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AimerDaniil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值