03-邮箱发送验证码

1. 步骤和工具类

首先需要准备的东西 我这里以QQ邮箱为例。

  1. 点击 设置 ->账户,找到这个页面:

image-20200616230717936

  1. 拿到授权码 并保存好:

image-20200616230755407

  1. MailUtil 工具类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtil {
public static void main(String[] args) {
sendMail("邮件接收者@qq.com","发送的信息");
}

/**
* 外网邮件发送
*
* @param to
* @param code
*/
public static void sendMail(String to, String code) {
String myEmailAddr = "邮件发送者@qq.com";

// Session对象:
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.qq.com"); // 设置主机地址
// smtp.163.com
// smtp.qq.com
// smtp.sina.com
props.setProperty("mail.smtp.auth", "true");// 认证
// 2.产生一个用于邮件发送的Session对象
Session session = Session.getInstance(props);

// Message对象:
Message message = new MimeMessage(session);
// 设置发件人:
try {
// 4.设置消息的发送者
Address fromAddr = new InternetAddress(myEmailAddr);
message.setFrom(fromAddr);

// 5.设置消息的接收者 nkpxcloxbtpxdjai
Address toAddr = new InternetAddress(to);
// TO 直接发送 CC抄送 BCC密送
message.setRecipient(MimeMessage.RecipientType.TO, toAddr);

// 6.设置主题
message.setSubject("来自*****系统的验证码");
// 7.设置正文
message.setContent("这里是邮件的正文信息\n\n您的验证码为:" + code, "text/html;charset=UTF-8");

// 8.准备发送,得到火箭
Transport transport = session.getTransport("smtp");
// 9.设置火箭的发射目标
//transport.connect("smtp.163.com", "发送者@163.com", "biao********");
transport.connect("smtp.qq.com", myEmailAddr, "jxzk*******");//jxzk..这个就是你的授权码
// 10.发送
transport.sendMessage(message, message.getAllRecipients());

// Transport对象:
// Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

2. 邮件验证码注册demo

源码结构(使用 Maven 配置demo):

image-20230610204532602

  • MailUtil.java 简单优化(只需要修改 myEmail16位邮箱授权码 即可)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.demo.utils;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtil {
/**
* 外网邮件发送
*
* @param to 收件人邮箱地址 收件人@xx.com
* @param code 传入的验证码
*/
public static void sendMail(String to, String code) {
String myEmail = "QQ邮箱@qq.com";
// Session对象:
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.qq.com"); // 设置主机地址
// smtp.163.com
// smtp.qq.com
// smtp.sina.com
props.setProperty("mail.smtp.auth", "true");// 认证
// 2.产生一个用于邮件发送的Session对象
Session session = Session.getInstance(props);

// Message对象:
Message message = new MimeMessage(session);
// 设置发件人:
try {
// 4.设置消息的发送者
Address fromAddr = new InternetAddress(myEmail);
message.setFrom(fromAddr);

// 5.设置消息的接收者 nkpxcloxbtpxdjai
Address toAddr = new InternetAddress(to);
// TO 直接发送 CC抄送 BCC密送
message.setRecipient(MimeMessage.RecipientType.TO, toAddr);

// 6.设置邮件标题
message.setSubject("来自 " + myEmail + " 的安全验证码");
// 7.设置正文
message.setContent("这里是邮件的正文信息\n\n您的验证码为:" + code, "text/html;charset=UTF-8");

// 8.准备发送,得到火箭
Transport transport = session.getTransport("smtp");
// 9.设置火箭的发射目标(第三个参数就是你的邮箱授权码)
//transport.connect("smtp.163.com", "发送者@163.com", "abcdefghabcdefgh");
transport.connect("smtp.qq.com", myEmail, "16位授权码");
// 10.发送
transport.sendMessage(message, message.getAllRecipients());

// Transport对象:
// Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}

public static String generateRandomCode(int length) {
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
while (sb.length() < length) {
// 0 ~ s.length()-1
int index = (new java.util.Random()).nextInt(s.length());
// 处理重复字符:每个新的随机字符在 sb 中使用indexOf()查找下标值,-1为没找到,即不重复
Character ch = s.charAt(index);
if (sb.indexOf(ch.toString()) < 0) {
sb.append(ch);
}
}
return sb.toString();
}
}
  • pom.xml 配置依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?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.demo</groupId>
<artifactId>mailTest</artifactId>
<version>1.0-SNAPSHOT</version>

<packaging>war</packaging>

<dependencies>
<!-- servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>

</project>
  • register.jsp 简陋但极速的注册页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>邮箱验证码测试</title>
<script src="${pageContext.request.contextPath}/js/jquery-3.5.1.min.js"></script>
<script>
$(function () {
sendMail();
});

// 异步请求发送邮件
var code;
function sendMail() {
$("#sendMailBtn").click(function () {
var emailAddr = $("#emailAddr").val();
$.ajax({
type: "post",
url: "${pageContext.request.contextPath}/toSendMail",
async: false, //为了拿到验证码返回,需使用同步,ajax 执行完,才 return code
data:{
"email": emailAddr
},
success: function (data) {
console.log("收到:" + data);
code = data;
},
});
$('#mailSpan').text("√ 邮件已发送!");
});

return code;
}

// form表单根据邮件验证码输入是否一致,决定是否拦截提交
function checkAll() {
var code = $("input[name='mailCode']").val();
var sysCode = sendMail();
console.log(code + " === " + sysCode);
return sysCode === code;
}
</script>
</head>
<body>

<h2>Mailbox Verification:</h2>
<br>
<form action="${pageContext.request.contextPath}/register" method="post" onsubmit="return checkAll()">
账号:<input type="text" name="username"/> <br><br>
密码:<input type="password" name="password"/> <br><br>
邮箱:<input type="email" name="email" id="emailAddr"/>
<%-- 点击按钮进入异步请求,发送邮箱验证码 --%>
<input type="button" value="发送验证码" id="sendMailBtn">
<span id="mailSpan" style="color: green"></span><br><br>
邮箱验证码:<input type="text" name="mailCode"> <br><br>
<input type="submit" value="注册" />
</form>

</body>
</html>

  • SendMailServlet.java 生成并相应 邮箱验证码 到页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.demo.controller;

import com.demo.utils.MailUtil;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.logging.Logger;

@WebServlet(name = "SendMailServlet", urlPatterns = "/toSendMail")
public class SendMailServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String emailAddr = request.getParameter("email");
String randomCode = MailUtil.generateRandomCode(5);

MailUtil.sendMail(emailAddr, randomCode);
// 响应异步请求(内容为邮箱验证码)
response.getWriter().write(randomCode);
Logger.getGlobal().info("邮件验证码已发送!");
}

protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doPost(request, response);
}
}
  • RegisterServlet.java 就一句,没啥说的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.demo.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("register success!!!");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
  • TestMail.java 测试类,你懂的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.demo.test;

import com.demo.utils.MailUtil;
import org.junit.Test;

import static com.demo.utils.MailUtil.sendMail;

public class TestMail {
@Test
public void test() {
String emailAddr = "3288983638@qq.com";
// 生成验证码,参数为 随机验证码位数
String randomCode = MailUtil.generateRandomCode(5);

sendMail(emailAddr, randomCode);
//sendMail("邮件接收者@qq.com","发送的信息");
}
}

3. 测试截图

image-20200617100406306

image-20200617100423920

image-20200617100507503

image-20200617100541261

4. pom 依赖

1
2
3
4
5
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>

03-邮箱发送验证码
https://janycode.github.io/2018/05/13/04_网页技术/10_验证码技术/03-邮箱发送验证码/
作者
Jerry(姜源)
发布于
2018年5月13日
许可协议