效果
前端代码
<li id="e_mail_li">
<span class="user_formtextlr" style="width: 120px;">*电子邮件:</span>
<span> <input type="text" style="width: 280px;" id="e_mail" name="select-key:e_mail" value="电子邮件" /></span>
<span class="user_formtextlr" style="width: 100px;">请填写有效的电子邮件地址。例如:admin@cnipr.com </span>
</li>
<li id="e_mail_li">
<span class="user_formtextlr" style="width: 120px;">*邮件验证码:</span>
<span>
<input type="text" name="code" id="code" placeholder="请输入邮箱的验证码" class="form-control" required>
<input type="button" name="btn" class="btn btn-default" id="btn" value="发送验证码" onclick="sendMessage()"/>
</span>
<span class="user_formtextlr" style="width: 100px;">点击发送邮箱验证码</span>
</li>
//邮箱验证码
$(function(){
$("#btn").click(function(){
//获取用户输入的邮箱
if($("#e_mail").val()){
$.ajax({
type:"POST",
url :"SendEmailServlet?random"+Math.random(),
data:{
//将邮箱作为参数传给后端
email:$("#e_mail").val(),
},
success:function(data){
alert("验证码发送成功,请注意查收。");
},
})
}else{
alert("邮箱发送失败");
}
}
);
});
//验证码倒计时
var InterValObj; //timer变量,控制时间
var count = 60; //间隔函数,1秒执行
var curCount;//当前剩余秒数
function sendMessage() {
curCount = count;
//attr()返回被选中的元素属性值并替换为括号中内容,本次将该按钮变为不可用
$("#btn").attr("disabled", "true");
$("#btn").val(curCount + "秒后可重新发送");
//window.setInterval(C,T)按照指定周期调用函数或计算表达式,C:定时要执行的Js代码,T:指定时间(毫秒)
//启动计时器,1秒执行一次请求后台发送验证码
InterValObj = window.setInterval(SetRemainTime, 1000);
}
//timer处理函数
function SetRemainTime() {
if (curCount == 0) {
window.clearInterval(InterValObj);//停止计时器
$("#btn").removeAttr("disabled");//启用按钮
$("#btn").val("重新发送验证码");
} else {
curCount--;
$("#btn").val(curCount + "秒后可重新发送");
}
}
后端代码
import cn.gwssi.di.user.util.JavaMailUtil;
import cn.gwssi.di.user.util.RandomUtil;
import cn.gwssi.di.user.util.htmlText;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
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;
import java.util.Properties;
@WebServlet("/SendEmailServlet")
public class SendEmailServlet extends HttpServlet {
//定义程序序列化ID。
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("邮箱发送功能");
try {
//获取前台传来的参数
String email = req.getParameter("email");
// 给用户输入的邮箱发送邮件
JavaMailUtil.receiveMailAccount = email;
// 1、创建参数配置,用于连接邮箱服务器的参数配置
Properties props = new Properties();
// 允许debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置右键服务器的主机名
props.setProperty("mail.host", JavaMailUtil.emailSMTPHost);
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 2、根据配置创建会话对象,用于和邮件服务器交互
Session session = Session.getInstance(props);
// 设置debug,可以查看详细的发送log
session.setDebug(true);
// 3、创建一封邮件
String code = RandomUtil.getRandom();
System.out.println("邮箱验证码:" + code);
String html = htmlText.html(code);
MimeMessage message = JavaMailUtil.creatMimeMessage(session,JavaMailUtil.emailAccount,JavaMailUtil.receiveMailAccount, html);
// 4、根据session获取邮件传输对象
Transport transport = session.getTransport();
// 5、使用邮箱账号和密码连接邮箱服务器emailAccount必须与message中的发件人邮箱一致,否则报错
transport.connect(JavaMailUtil.emailAccount, JavaMailUtil.emailPassword);
// 6、发送邮件,发送所有收件人地址
transport.sendMessage(message, message.getAllRecipients());
// 7、关闭连接
transport.close();
// 写入session
req.getSession().setAttribute("code", code);
} catch (Exception e) {
e.printStackTrace();
req.getSession().setAttribute("error", "邮件发送失败");
}
}
}
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;
public class JavaMailUtil {
// 发件人的邮箱
public static String emailAccount = "此处填写用于发件人的邮箱";
// 发件人邮箱授权码(邮箱内可获取)
public static String emailPassword = "发件人邮箱的授权码";
// 发件人邮箱服务地址(邮箱内可获取)
public static String emailSMTPHost = "发件人邮箱的服务地址";
// 收件人邮箱
public static String receiveMailAccount = "";
public static MimeMessage creatMimeMessage(Session session, String sendMail, String receiveMail, String html) throws MessagingException, IOException {
// 1、创建一封邮件对象
MimeMessage message = new MimeMessage(session);
// 2、From:发件人
message.setFrom(new InternetAddress(sendMail, "发送邮件的标题", "UTF-8"));
// 3、To:收件人(可以增加多个收件人:抄送或者密送)
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "张三", "UTF-8"));
// 4、Subject:邮件主题
message.setSubject("邮箱验证","UTF-8");
// 5、Content:邮件正文(可以使用Html标签)
message.setContent(html,"text/html;charset=UTF-8");
// 6、设置发送时间
message.setSentDate(new Date());
// 7、保存设置
message.saveChanges();
return message;
}
}
/**
* Math.random()获取0-1之间的随机数
* Math.floor()向下取整
* Math.floor(Math.random())获取指定范围内的整数
* 例:Math.random()*52 0≤X<52
* Math.random()*52+1 1≤X<53
* Math.floor(Math.random()*52+1) 1-52随机整数
*/
public class RandomUtil {
public static void main(String[] args) {
// 控制台打印
System.out.println(RandomUtil.getRandom());
}
// 随机验证码6位
public static String getRandom() {
String[] letters = new String[] {
"q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
"A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
"0","1","2","3","4","5","6","7","8","9"};
String code ="";
//生成六位随机验证码
for (int i = 0; i < 6; i++) {
//letter长度的随机六位整数
code = code + letters[(int)Math.floor(Math.random()*letters.length)];
}
return code;
}
}
public class htmlText {
// 返回页面Html携带的6位随机码
public static String html(String code) {
String html = "Email地址验证<br/>"+"这封邮件由【我】发送。<br/>"+"你收到这封邮件是【我】进行新用户注册使用这个地址。<br/>"+"请将下面的验证码输入到提示框即可:<h3 style='color:red;'>" + code + "</h3><br/>";
return html;
}
}
账号用来记录日常学习到的代码知识,本篇文章也是在CSDN上跟另一位作者的文章学习而来,下面附上原地址,感谢!