首先需要准备的东西 我这里以QQ邮箱为例。
设置
->账户
,找到这个页面:package com.mailtest.demo;
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();
}
}
}
源码结构(使用 Maven 配置demo):
myEmail
和 16位邮箱授权码
即可)。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();
}
}
<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.0modelVersion>
<groupId>com.demogroupId>
<artifactId>mailTestartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.sun.mailgroupId>
<artifactId>javax.mailartifactId>
<version>1.6.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>RELEASEversion>
<scope>compilescope>
dependency>
dependencies>
project>
<%@ 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>
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);
}
}
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);
}
}
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 = "[email protected]";
// 生成验证码,参数为 随机验证码位数
String randomCode = MailUtil.generateRandomCode(5);
sendMail(emailAddr, randomCode);
//sendMail("邮件接收者@qq.com","发送的信息");
}
}