先放一张程序的预览图
工程下载链接
链接:https://pan.baidu.com/s/1Lrm8d6mBemKIWKd0ll0E9g
提取码:vrwh
设置->账户->开启POP3/SMTP服务
开启后会获取一个授权码,记住这个授权码,这个相当于是一个密码。
import java.util.Random;
public class VCodeUtill {
/*
* 生成n位随机验证码,包括数字和大小写字母
* @param 验证码长度
* @return n位验证码
*/
public static String verifyCode(int n) {
StringBuilder strB = new StringBuilder();
Random rand = new Random();
for(int i = 0; i < n; i++) {
int r1 = rand.nextInt(3);
int r2 = 0;
switch (r1) { // r2为ascii码值
case 0: // 数字
r2 = rand.nextInt(10) + 48; // 数字:48-57的随机数
break;
case 1:
r2 = rand.nextInt(26) + 65; // 大写字母
break;
case 2:
r2 = rand.nextInt(26) + 97; // 小写字母
break;
default:
break;
}
strB.append((char)r2);
}
return strB.toString();
}
}
这一步需要java.mail.jar下载链接
import java.util.Date;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtil {
private static String fromEmail = "[email protected]"; // 发件人账号
private static String fromEmailPw = "bgyqinrqpbdebdif"; // 发件人密码
private static String myEmailSMTPHost = "smtp.qq.com"; // 发件邮箱服务器
private static Properties props; // 用于参数配置
private static Session session; // 用于创建会话对象
private String vCode;
public static EmailUtil instance = new EmailUtil();
/*
* 获取验证码
* @return 验证码字符串
*/
public String getVCode() {
return vCode;
}
/*
* 构造函数,配置属性
*/
private EmailUtil() {
props = new Properties();
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
session = Session.getInstance(props);
// session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
}
/*
* 构建邮件内容
* @param 收件人
* @return 发送邮件内容
*/
public MimeMessage createMailContent(String toEmail) throws Exception, MessagingException {
MimeMessage message = new MimeMessage(session);
// 发件人
message.setFrom(new InternetAddress(fromEmail, "验证码发送系统", "UTF-8"));
// 收件人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toEmail));
// 邮件主题
message.setSubject("验证码", "UTF-8");
// 邮件正文
vCode = VCodeUtill.verifyCode(6);
message.setContent("您好,您的验证码是:"+vCode+"。", "text/html;charset=UTF-8");
// 设置发件时间
message.setSentDate(new Date());
// 保存设置
message.saveChanges();
return message;
}
/*
* 发送邮件
* @param 收件人
*/
public void sendEmail(String toEmail) throws Exception {
Transport transport = session.getTransport();
transport.connect(fromEmail, fromEmailPw);
MimeMessage message = createMailContent(toEmail); // 邮件内容
transport.sendMessage(message, message.getAllRecipients());
System.out.println("验证码发送成功!");
// 关闭连接
transport.close();
}
}
准备:jquery-1.11.3.js下载链接
简单的前端界面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML>
<html>
<head>
<base href="<%=basePath%>">
<title>Java web邮箱验证码</title>
</head>
<body>
<form id="form0" name="form0" AUTOCOMPLETE="OFF">
<table>
<tr height="35px">
<td >收件邮箱:</td>
<td>
<input type="text" name="email" id="email" placeholder="输入邮箱" />
</td>
<td>
<button id="btnGetVcode" style="cursor:pointer">获取验证码</button>
</td>
</tr>
<tr height="35px">
<td >验证码:</td>
<td>
<input type="text" name="vcode" id="vcode" placeholder="输入验证码"/>
</td>
<td id="message"></td>
</tr>
</table>
<a target="_self">
<button type="button" id="btnVerify" style="cursor:pointer">验证</button></a>
</form>
<!-- 引入jQuery -->
<script type="text/javascript" src="js/jquery-1.11.3.js"></script>
<script type="text/javascript" src="js/jsEmail.js"></script>
</body>
</html>
对应的javascript程序:
var time0 = 60;
var time = time0;
var t; // 用于验证按钮的60s计时
$(document).ready(function() {
// 获取验证码按钮
$("#btnGetVcode").click(function() {
var btnGet = document.getElementById("btnGetVcode");
btnGet.disabled = true; // 为了防止多次点击
$.ajax({
url: 'EmailServlet?method=getVCode',
type: 'post',
data: {email: $("input[name='email']").val()},
dataType: 'text',
success: function(msg) {
if(msg == -1){
window.alert("请输入正确的邮箱!");
btnGet.disabled = false;
}
else{
useChangeBTN(); // 控制下一次重新获取验证码
}
},
error:function(msg){
}
});
});
// 验证按钮
$("#btnVerify").click(function() {
var message = document.getElementById("message"); // 显示提示信息
$.ajax({
url: 'EmailServlet?method=verify',
type: 'post',
data: {vcode: $("input[name='vcode']").val()},
dataType: 'text',
success: function(msg) {
if(msg == 1){
message.innerHTML = "验证码正确!";
$("#message").css("color","green");
}
else{
message.innerHTML = "验证码错误!";
$("#message").css("color","red");
}
},
error:function(msg){
}
});
});
});
//修改按钮,控制验证码重新获取
function changeBTN(){
if(time > 0){
$("#btnGetVcode").text("("+time+"s)"+"重新获取");
time = time - 1;
}
else{
var btnGet = document.getElementById("btnGetVcode");
btnGet.disabled = false;
$("#btnGetVcode").text("获取验证码");
clearInterval(t);
time = time0;
}
}
function useChangeBTN(){
$("#btnGetVcode").text("("+time+"s)"+"重新获取");
time = time - 1;
t = setInterval("changeBTN()", 1000); // 1s调用一次
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
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 util.EmailUtil;
@SuppressWarnings("serial")
@WebServlet(urlPatterns={"/EmailServlet"})
public class EmailServlet extends HttpServlet {
private String email; // 获取的收件人邮箱
private String vCode; // 后台产生的验证码
private String vCodeReceive; // 接收到前端输入的验证码
private String method; // 要接收的方法
private PrintWriter out; // 输出流
private EmailUtil emailUtil = EmailUtil.instance;
public EmailServlet() {
// TODO Auto-generated constructor stub
System.out.println("初始化");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
/*
* 在此实现servlet
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/html");
//语言编码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
out = resp.getWriter();
// 获取来自前端的参数
email = req.getParameter("email");
vCodeReceive = req.getParameter("vcode");
method = req.getParameter("method");
switch (method) {
case "getVCode":
mGetVCode();
break;
case "verify":
mVerify();
break;
default:
break;
}
out.flush();
out.close();
}
/*
* 产生验证码,并发送邮件
*/
private void mGetVCode() {
// TODO Auto-generated method stub
if(!isEmail(email)) { // 邮箱不正确
out.print(-1);
return;
}
try {
emailUtil.sendEmail(email);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vCode = emailUtil.getVCode();
System.out.println("验证码为:" + vCode);
out.print(1);
}
/*
* 邮箱正确性检测
* @param 邮箱字符串
* @return true/false
*/
private boolean isEmail(String email) {
if(email.length() == 0 || email == null) {
return false;
}
// 正则表达式验证邮箱
Pattern pattern = Pattern.compile("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
return pattern.matcher(email).matches();
}
/*
* 验证码验证
*/
private void mVerify() {
// TODO Auto-generated method stub
if(vCode.equals(vCodeReceive)) {
out.print(1);
}
else {
out.print(-1);
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
}