java动态发送邮箱验证

最近这两天看了一下java邮箱验证的相关资料,发送邮箱的关键词是javaMail,因为现在这个邮箱验证很常见,在写javaWeb时基本上都会用到邮箱验证,以确保登录者的身份。

因为要用到所以学习了一下,并做了一个简单的例子。

这个邮箱验证的设计思路是:需要建立两个表,一个是存储验证码的表、另一个是存储用户名、密码、邮箱号的表。验证码可以自动生成,调用javaMail中的发短信的方法,

实现短信的发送同时将生成的验证码传输到邮箱中,用户点击邮箱进行验证,如果验证信息正确,便可以完成注册。反之,注册失败。

下面是是实现的源码(这里只写核心代码):

Mailer.java 代码(嘿嘿,这个在网上找的源码,自己稍微改变了一下。)

package edu.hpu.sendemail.util;


import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Mailer {
/** javamail session对象. */
protected Session session;
/** 发信地址 */
protected String from;
/** 信的标题*/
protected String subject;
/** 存放字符串形式的收信地址 */
protected ArrayList toList = new ArrayList();
/** 抄送地址*/
protected ArrayList ccList = new ArrayList();
/** 暗送地址 */
protected ArrayList bccList = new ArrayList();
/** 信的文本内容*/
protected String body;
/** SMTP服务器地址*/
protected String mailHost;
/**是否在控制台打印信息*/
protected boolean verbose=true;
/** Get from */
public String getFrom() {
return from;
}
public void setFrom(String fm) {
from = fm;
}
public String getSubject() {
return subject;
}
public void setSubject(String subj) {
subject = subj;
}
public ArrayList getToList() {
return toList;
}
public void setToList(ArrayList to) {
toList = to;
}
public void setToList(String s) {
toList = tokenize(s);
}
public void addTo(String to) {
toList.add(to);
}
public ArrayList getCcList() {
return ccList;
}
public void setCcList(ArrayList cc) {
ccList = cc;
}
public void setCcList(String s) {
ccList = tokenize(s);
}
public void addCc(String cc) {
ccList.add(cc);
}
public ArrayList getBccList() {
return bccList;
}
public void setBccList(ArrayList bcc) {
bccList = bcc;
}
public void setBccList(String s) {
bccList = tokenize(s);
}
public void addBcc(String bcc) {
bccList.add(bcc);
}
public String getBody() {
return body;
}
public void setBody(String text) {
body = text;
}
public boolean isVerbose() {
return verbose;
}
public void setVerbose(boolean v) {
verbose = v;
}


public boolean isComplete() { //
if (from == null || from.length()==0) {
System.err.println("doSend: no FROM");
return false;
}
if (subject == null || subject.length()==0) {
System.err.println("doSend: no SUBJECT");
return false;
}
if (toList.size()==0) {
System.err.println("doSend: no recipients");
return false;
}
if (body == null || body.length()==0) {
System.err.println("doSend: no body");
return false;
}
if (mailHost == null || mailHost.length()==0) {
System.err.println("doSend: no server host");
return false;
}
return true;
}
public void setServer(String s) {
mailHost = s;
}
/** Send the message.
*/
public synchronized void doSend() throws MessagingException {
if (!isComplete())
throw new IllegalArgumentException("doSend called before message was complete");
Properties props = new Properties();
props.put("mail.smtp.host", mailHost);
props.put("mail.smtp.auth", "true");//指定是否需要SMTP验证
// Create the Session object
if (session == null) {
session = Session.getDefaultInstance(props, null);
if (verbose)
session.setDebug(true); // Verbose!
}
// create a message
final Message mesg = new MimeMessage(session);
InternetAddress[] addresses;
// TO Address list
addresses = new InternetAddress[toList.size()];
for (int i=0; i<addresses.length; i++)
addresses[i] = new InternetAddress((String)toList.get(i));
mesg.setRecipients(Message.RecipientType.TO, addresses);
// From Address
mesg.setFrom(new InternetAddress(from));
// CC Address list
addresses = new InternetAddress[ccList.size()];
for (int i=0; i<addresses.length; i++)
addresses[i] = new InternetAddress((String)ccList.get(i));
mesg.setRecipients(Message.RecipientType.CC, addresses);
// BCC Address list
addresses = new InternetAddress[bccList.size()];
for (int i=0; i<addresses.length; i++)
addresses[i] = new InternetAddress((String)bccList.get(i));
mesg.setRecipients(Message.RecipientType.BCC, addresses);
// The Subject
mesg.setSubject(subject);     //此处是标题,可以提取数据库填入的内容。
// Now the message body.
mesg.setText(body);
Transport transport =session.getTransport("smtp");
transport.connect(mailHost, "15239751075", "li1314li");
transport.sendMessage(mesg, mesg.getAllRecipients());
}
protected ArrayList tokenize(String s) {
ArrayList al = new ArrayList();
StringTokenizer tf = new StringTokenizer(s, ",");
// For each word found in the line
while (tf.hasMoreTokens()) {
// trim blanks, and add to list.
al.add(tf.nextToken().trim());
}
return al;
}
public void sendMail(String UUID,String Md5,String stu_email){
Mailer mailer = new Mailer();
mailer.setServer("smtp.163.com");
mailer.setFrom("15239751075@163.com");
mailer.addTo(stu_email);
mailer.setSubject("i优停车官网");
String m = "点击激活";
mailer.setBody("点击激活验证"+ //设置路径
"http://localhost:8080/SendEmail/mailVerifySer?uuid="+UUID+"&md5="+Md5+"");

try{
mailer.doSend();
}catch (MessagingException e) {}
}
}
 AddStuSer.java 代码(这个是用户注册提交的servlet代码。)

package edu.hpu.sendemail.Servlet;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import edu.hpu.sendemail.dao.InSendEmail;
import edu.hpu.sendemail.dao.SendEmailImpl;
import edu.hpu.sendemail.model.Student;
import edu.hpu.sendemail.model.Verify;
import edu.hpu.sendemail.util.Mailer;
import edu.hpu.sendemail.util.TimeStamp;


public class AddStuSer extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
 
String stu_name = request.getParameter("stu_name");
String stu_password = request.getParameter("stu_password");
String stu_email = request.getParameter("stu_email");
 
Mailer sendemail = new Mailer();
TimeStamp ts = new TimeStamp();
String uuid = ts.UUID();
String md5 = ts.MD5(stu_name);    //生成验证码。
sendemail.sendMail(uuid,md5,stu_email);   //调用发送email方法
 
Student student = new Student();
student.setStu_email(stu_email);
student.setStu_name(stu_name);
student.setStu_password(stu_password);
 
 Verify verify = new Verify();
 verify.setRandMd5(md5);
 verify.setStu_nameMd5(uuid);
 verify.setStu_name(stu_name);
 
 InSendEmail is = new SendEmailImpl();
 boolean flag = is.addVerify(verify);
 if(flag){
 request.getSession().setAttribute("student", student);   //用session将数据发送到另一个servlet
 response.sendRedirect("index.jsp");   //暂时先跳转到这
 }
}
}
MailVerifSery.java 代码(这里是用户点击邮箱验证的servlet,如果验证成功,将信息注册到数据库中。并显示账号已成功激活)

package edu.hpu.sendemail.Servlet;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import edu.hpu.sendemail.dao.InSendEmail;
import edu.hpu.sendemail.dao.SendEmailImpl;
import edu.hpu.sendemail.model.Student;
import edu.hpu.sendemail.util.*;


public class mailVerifySer extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
 
HttpSession session = request.getSession();
String UUID = request.getParameter("uuid");
String Md5 = request.getParameter("md5");
Student student = (Student) session.getAttribute("student");
PrintWriter out = response.getWriter();
InSendEmail is = new SendEmailImpl();
boolean flag = is.getVerify(UUID,Md5);
if(flag){   //说明邮箱验证正确。
InSendEmail  ise = new SendEmailImpl();
boolean falgV = ise.delVerify(student.getStu_name());
System.out.println("falgV"+falgV);
boolean flagS = ise.addStudent(student);  //向表中添加信息
if(flagS){
out.print("账号已激活");
}
}
}
}

SendEmailImpl.java 代码(在这个验证过程中要实现的方法)

package edu.hpu.sendemail.dao;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import edu.hpu.sendemail.model.Student;
import edu.hpu.sendemail.model.Verify;
import edu.hpu.sendemail.util.DBC;


public class SendEmailImpl implements InSendEmail {


public boolean addStudent(Student student) {
boolean flag = false;
Connection conn = null;
PreparedStatement pst = null;
conn = DBC.getConnection();
String sql = "insert into student (stu_name,stu_password,stu_email)values(?,?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(3, student.getStu_email());
pst.setString(2, student.getStu_password());
pst.setString(1, student.getStu_name());
if(pst.executeUpdate()>0){
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}




public boolean addVerify(Verify verify) {
boolean flag = false;
Connection conn = null;
PreparedStatement pst = null;
conn = DBC.getConnection();
String sql = "insert into verify (stu_name,stu_nameMd5,randMd5)values(?,?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(3, verify.getRandMd5());
pst.setString(2, verify.getStu_nameMd5());
pst.setString(1, verify.getStu_name());
if(pst.executeUpdate()>0){
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}


public boolean delVerify(String stuName) {
boolean flag =false; 
Connection conn = null;
PreparedStatement pst = null;
conn = DBC.getConnection();
String sql = "delete from verify where stu_nameMd5 = '"+stuName+"'";
try {
pst = conn.prepareStatement(sql);
if(pst.executeUpdate()>0){
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}

return flag;
}


public boolean getVerify(String stuNameMd5, String randMd5) {
boolean flag =false; 
Connection conn = null;
Statement st = null;
ResultSet rs = null;
conn = DBC.getConnection();
String sql = "select stu_name from verify where stu_nameMd5 = '"+stuNameMd5+"' and randMd5='"+randMd5+"'";
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
if(rs.next()){
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}

return flag;
}
}

}

代码就粘到这吧,一下就是javaBean和一个jsp界面了。这个是自己跟着平时注册账号的感觉写的,然后又在网上找的一些资料。不知道正规的这个邮箱验证是什么设计思路。

如果感觉有不对的地方,希望大家提出来,批评指教才能进步。

  • 0
    点赞
  • 1
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论

打赏作者

阿卧

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值