说明:以讲解Email操作为主,不过多描述数据库操作,有javaweb基础的话,我相信能够举一反三。
必要的准备工作(略):
1.导入jar包
需要一个发送邮件的jar包 : javax.mail .jar
下载jar包:链接:https://pan.baidu.com/s/1t9G_V2aaa_FbHx51pbB1Xg
提取码:s4a5
2.(略写)数据库相关操作(以我的为例),这里不描述数据库的创建以后面截图为准。
UserDaoImpl.java
@Override
public User queryUserByEmail(String email) {
Connection conn=null;
User user=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
String sql="select * from userrejister where email=?";
Object[] params={email};
//DBUtil为工具类
rs=DBUtil.executeQuery(sql, params);
if(rs.next()){
String username=rs.getString("username");
String password=rs.getString("password");
String school=rs.getString("school");
String sex=rs.getString("sex");
String tel=rs.getString("tel");
Integer Id=rs.getInt("id");
String age=rs.getString("age");
String Email=rs.getString("email");
user=new User(username,password,school,sex,tel,Id,age,Email);
}
return user;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}finally{
JDBCUtil.close(rs, pstmt, conn);
}
}
UserServiceImpl.java
@Override
public User getUserByEmail(String email) {
return ud.queryUserByEmail(email);
}
DBUtil.java
public static Connection conn=null;
public static PreparedStatement pstmt=null;
public static ResultSet rs=null;
public static PreparedStatement createPreparedStatement(String sql,Object[] params){
try {
conn=JDBCUtil.getConnection();
pstmt=conn.prepareStatement(sql);
if(params!=null){
for(int i=0;i<params.length;i++){
pstmt.setObject(i+1, params[i]);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pstmt;
}
public static ResultSet executeQuery(String sql,Object[] params){
//这里的rs不能关闭,因为返回的是结果集,其他类还要使用!!!!!。
try {
pstmt=createPreparedStatement(sql, params);
rs=pstmt.executeQuery();
}catch (SQLException e) {
e.printStackTrace();
return null;
}
return rs;
}
User.java(实体类)
package com.entity;
import java.util.*;
import java.sql.*;
public class User {
private String password;
private String school;
private String sex;
private String tel;
private Integer id;
private String age;
private String email;
private String username;
}
3.数据库创建
4.写jsp测试页面
input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>找回密码-图书管理系统</title>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div style="text-align: center" width="300px" height="200px">
<form action="GetBackPassword" method="post">
<input type="email" name="email" id="email" width="100px"
height="60px" style="margin-top: 100px" placeholder="请输入您的邮箱地址"
required> <br>
<br>
<button type="submit" class="btn btn-success" id="button"
width="100px" height="60px">找回密码</button>
</form>
<br>
<br>
<button type="button" class="btn btn-primary" id="button"
onclick="backLogin()" width="100px" height="60px">返回登录页面</button>
</div>
<script type="text/javascript">
function backLogin() {
window.location.href = "login.jsp"
}
</script>
</body>
</html>
发送邮件类 和 Servlet代码
发送邮件类
package com.bookms.util;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
public class SendMail {
//hpzy_rz_liuhx@163.com
// 发件人的邮箱账号如:xxx@163.com
public static String sendEmailAccount = "";
// 发件人的邮箱的授权码(自己在邮箱服务器中开启并设置)
public static String sendEmailPassword = "";
// 发件人邮箱的SMTP服务器地址,如:smtp.163.com
public static String sendEmailSMTPHost = "smtp.163.com";
// 收件人的邮箱账号
public static String receiveMailAccount = "";
// 把发送邮件封装为函数,参数为收件人的邮箱账号和要发送的内容
public void sendMail(String receiveMailAccount, String mailContent) {
// 创建用于连接邮件服务器的参数配置
Properties props = new Properties();
// 设置使用SMTP协议
props.setProperty("mail.transport.protocol", "smtp");
// 设置发件人的SMTP服务器地址
props.setProperty("mail.smtp.host", sendEmailSMTPHost);
// 设置需要验证
props.setProperty("mail.smtp.auth", "true");
// 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getInstance(props);
// 设置debug模式,便于查看发送过程所产生的日志
session.setDebug(true);
try {
// 创建一封邮件
MimeMessage message = createMimeMessage(session, sendEmailAccount, receiveMailAccount, mailContent);
// 根据 Session 获取邮件传输对象
Transport transport = session.getTransport();
transport.connect(sendEmailAccount, sendEmailPassword);
// 发送邮件, 发到所有的收件地址, 通过message.getAllRecipients() 可以获取到在创建邮件对象时添加的所有收件人
transport.sendMessage(message, message.getAllRecipients());
// 关闭连接
transport.close();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param session
* 和服务器交互的会话
* @param sendMail
* 发件人邮箱
* @param receiveMail
* 收件人邮箱
* @return
* @throws Exception
*/
public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail,
String mailContent) throws Exception {
// 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 设置发件人姓名和编码格式
message.setFrom(new InternetAddress(sendMail, "图书管理系统", "UTF-8"));
// 收件人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "尊敬的用户", "UTF-8"));
// 设置邮件主题
message.setSubject("找回密码提醒", "UTF-8");
// 设置邮件正文
message.setContent(mailContent, "text/html;charset=UTF-8");
// 设置发件时间
message.setSentDate(new Date());
// 保存设置
message.saveChanges();
return message;
}
}
具体说明:
发件人的邮箱:这里可以自己手动设置
**发件人的邮箱授权码(重点):也需要手动设置,稍后会已截图的形式呈现哪里找授权码。
收件人的邮箱账号:这里不用手动设置,利用JSP传递邮箱给Servlet,再传递给此变量即可。注意:jsp输入的邮箱要你在数据库中保存好了的呀...
授权码获得途径:自己设置授权码,然后在sendEmail中手动添加进去,即可。
Servlet类
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setHeader("Content-Type","text/html;charset=utf-8");
//获取用户的邮箱
String email = request.getParameter("email");
PrintWriter out = response.getWriter();
//实例化一个发送邮件的对象
SendMail mySendMail = new SendMail();
//根据邮箱找到该用户信息
IUserService service=new UserServiceImpl();
User user = service.getUserByEmail(email);
if(user!=null) {
//设置收件人和消息内容
mySendMail.sendMail(email, "图书管理系统提醒,您的密码为:"+user.getPassword());
out.println("<script>alert('恭喜,找回密码成功');window.location.href='login.jsp'</script>");
}
out.println("<script>alert('该邮箱尚未注册!请重新输入');window.location.href='retrievePassword.jsp'</script>");
}
最后会将密码发送给该邮箱的用户: