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 '手机号码',
`userVerificationCode` int(6) DEFAULT NULL COMMENT '验证码',
`userActivationCode` 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=1007 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/>
</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>
<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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<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>
<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
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@TableName("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;
private Integer permissionid;
private boolean status;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Timestamp registerdata;
@TableField(exist = false)
private String vipname;
@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
mail:
host: smtp.qq.com
username: Xxx@qq.com
password:
protocol: smtp
properties.mail.smtp.auth: true
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
mybatis-plus:
type-aliases-package: com.demo.pojo
mapper-locations: classpath:/mybatis/*.xml
configuration:
map-underscore-to-camel-case: true
debug: false
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
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
default-encoding: utf-8
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.starttls.enable=true
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({
type: "POST",
url: "http://localhost:8080/fkxinli/register",
data:$("#f1").serialize(),
success: function(data) {
document.write(data);
},
error: function(data) {
}
})
}
function sendEmail(){
$.ajax({
type: "POST",
url: "http://localhost:8090/email/sendEmail",
data:$("#f1").serialize(),
success: function(data) {
alert(data);
},
error: function(data) {
}
})
}
function verificationEmail(){
$.ajax({
type: "POST",
url: "http://localhost:8090/email/verificationEmail",
data:$("#f1").serialize(),
success: function(data) {
alert(data);
},
error: function(data) {
}
})
}
<!--返回首页-->
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、测试
后端代码,写的比较简单,仅仅测试邮箱是否能够发送验证码
|