java:email邮箱的使用
本博文根据菜鸟教程的知识完成:链接
案列分析:当在登录的时候发现忘记密码如何通过邮箱获取验证码的方式修改密码?
本文设计Cookie的知识,数据库连接池的知识。可以提前点击观看。
首先看修改的页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>修改密码</title> </head> <body> <form action="/demo2/emailservletdemo1"> 用户名:<input type="text" name="username"><br> 邮箱:<input type="text" name="useremail"><br> <input type="submit" name="提交"> </form> </body> </html>
重置密码的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>重置密码</title> </head> <body> <form action="/demo2/servletdemo1"> 新密码:<input type="text" name="password"><br> 验证码:<input type="text" name="code"><br> <input type="submit" name="提交"> </form> </body> </html>
发送邮箱的工具类
import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class Emailutils{ /*用于给客户发送邮箱验证码*/ public String SendUser="2269435134@qq.com";//发件人的邮箱 public String SendPass="jmknqhltsnutdjbc";//发件人的授权码 public String host = "smtp.qq.com"; //QQ 邮件服务器 //固定文本模板 public void MailSendText(String AcceptUser,String code){ // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.auth", "true"); // 获取默认session对象 Session session = Session.getDefaultInstance(properties,new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(SendUser,SendPass); //发件人邮件用户名、授权码 } }); try{ // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From: 头部头字段 message.setFrom(new InternetAddress(SendUser)); // Set To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(AcceptUser)); // Set Subject: 头部头字段 message.setSubject("邮箱验证码"); // 设置消息体 String text="你好,你的邮箱验证码是"+code+"有效期是5分钟"; message.setText(text); // 发送消息 Transport.send(message); System.out.println("发送成功"); }catch (MessagingException mex) { mex.printStackTrace(); } } //自定义文本模板 public void MailSendText(String AcceptUser,String line,String text){ // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.auth", "true"); // 获取默认session对象 Session session = Session.getDefaultInstance(properties,new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(SendUser,SendPass); //发件人邮件用户名、授权码 } }); try{ // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From: 头部头字段 message.setFrom(new InternetAddress(SendUser)); // Set To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(AcceptUser)); // Set Subject: 头部头字段 message.setSubject(line); // 设置消息体 message.setText(text); // 发送消息 Transport.send(message); System.out.println("发送成功"); }catch (MessagingException mex) { mex.printStackTrace(); } } }
开始发送邮箱验证码
import com.web.utils.Druidutils; import com.web.utils.Emailutils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Random; @WebServlet("/emailservletdemo1") public class EmailSevletDemo1 extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); String username=req.getParameter("username"); String useremail=req.getParameter("useremail"); String sql="select *from user where username=? and useremail=?"; Connection conn= null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn = Druidutils.getConnection(); pstmt=conn.prepareStatement(sql); pstmt.setString(1,username); pstmt.setString(2,useremail); conn.setAutoCommit(false); rs=pstmt.executeQuery(); conn.commit(); if(rs.next()){//存在 String str = "0123456789"; Random ran = new Random(); StringBuilder sb = new StringBuilder(); //生成验证码 for(int i=0;i<6;i++){ int index = ran.nextInt(str.length()); //获取字符 char ch = str.charAt(index);//随机字符 sb.append(ch); } String str1=sb.toString(); System.out.println("生成的验证码是"+str1); Emailutils email=new Emailutils(); email.MailSendText(useremail,str1);//发送邮件 Cookie c1=new Cookie("yanzhengma",str1); c1.setMaxAge(60*5); Cookie c2=new Cookie("username",username); c2.setMaxAge(60*5); resp.addCookie(c1); resp.addCookie(c2); System.out.println("验证成功,开始转发................"); req.getRequestDispatcher("chongzhi.jsp").forward(req,resp); }else{//不存在 System.out.println("不存在不得修改"); } }catch (SQLException throwables){ throwables.printStackTrace(); }finally { Druidutils.close(rs,pstmt,conn); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } }
修改密码操作
import com.web.utils.Druidutils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @WebServlet("/servletdemo1") public class ServletDemo1 extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Connection conn= null; PreparedStatement pstmt=null; ResultSet rs=null; String password=req.getParameter("password"); String yanzhengma=req.getParameter("code"); Cookie[] cookies=req.getCookies(); boolean flag=false; String username=""; String code=""; System.out.println("接收到的验证码是:"+yanzhengma); for(Cookie cookie:cookies){ if(cookie.getName().equals("username")){ username=cookie.getValue(); flag=true; } if (cookie.getName().equals("yanzhengma")){ code=cookie.getValue(); } } if(flag&&(code.equals(yanzhengma))){ String sql="update user set password=? where username=?"; try { conn = Druidutils.getConnection(); pstmt=conn.prepareStatement(sql); pstmt.setString(1,password); pstmt.setString(2,username); conn.setAutoCommit(false); int b1=pstmt.executeUpdate(); conn.commit(); if (b1>0){ System.out.println("密码重置成功"); }else{ System.out.println("密码重置失败"); } } catch (SQLException throwables) { throwables.printStackTrace(); }finally { Druidutils.close(rs,pstmt,conn); } }else{ System.out.println("验证码输出错误!!!"); } } }
一纸高中万里风,寒窗读破华堂空。
莫道长安花看尽,由来枝叶几相同?