关于JavaMail实现QQ邮箱发送邮件的实现(二)

时间:2021-10-02 18:59:26

前言:

  这篇文章所涉及的关键部分是在关于JavaMail实现QQ邮箱发送邮件的实现(一)的基础上完成的,所以请先阅读上一篇文章,以便更好的理解这一篇。这篇文章中实现的功能是,在用户注册的时候,通过系统邮箱向注册的邮箱发送一封激活邮件,在点击激活之后,完成用户的注册。

   需要的相关JAR包和配置文件下载:https://i.cnblogs.com/Files.aspx

一 引入相关JAR包

1.在新建的Java Web工程中的WebRoot-->WEB-INF-->lib下导入以下这个四个JAR包

关于JavaMail实现QQ邮箱发送邮件的实现(二)

 

2. 在Java Web工程中的src目录下导入c3p0配置文件

关于JavaMail实现QQ邮箱发送邮件的实现(二)

 

二  搭建好包结构和类结构

关于JavaMail实现QQ邮箱发送邮件的实现(二)

 

 三 数据库相关

1.创建MYSQL数据库

 1 /**
 2 * state 是激活状态,0:未激活 1:已经激活
 3 * code 是激活码
 4 */
 5 
 6 create database mail;
 7 use mail;
 8 create table user (
 9     id int primary key auto_increment,
10     username varchar(20) default null,
11     password varchar(20) default null, 
12     email varchar(30) default null,
13     state int(11) default null,
14     code varchar(64) default null
15 );

 

2.创建数据库类JDBCUtils.java (数据池连接)

 1 package com.mail.utils;
 2 
 3 import com.mchange.v2.c3p0.ComboPooledDataSource;
 4 
 5 public class JDBCUtils {
 6     private static String url = "jdbc:mysql://localhost:3306/mail";  //注意用自己的创建的数据库
 7     private static String user = "root";
 8     private static String passwd = "数据库登录密码";
 9     private static String driver = "com.mysql.jdbc.Driver";
10    
11     public static ComboPooledDataSource getDataSource() throws Exception{
12         ComboPooledDataSource cpds = new ComboPooledDataSource(); 
13         cpds.setDriverClass( driver);
14         cpds.setJdbcUrl( url );
15         cpds.setUser(user);                                  
16         cpds.setPassword(passwd);  
17         cpds.setMinPoolSize(5);                                     
18         cpds.setAcquireIncrement(5);
19         cpds.setMaxPoolSize(30);
20         cpds.setMaxIdleTime(60);
21         return cpds;
22     }
23 }

 

 四 核心代码

1.创建一个表单的注册页面register.jsp,该表单会提交到RegisterServlet上

 1 <!-- 用户注册的页面 -->
 2 
 3 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
 4 
 5 <%
 6 String path = request.getContextPath();
 7 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 8 %>
 9 
10 
11 
12 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
13 <html>
14   <head>
15     <base href="<%=basePath%>">
16     
17     <title>My JSP 'register.jsp' starting page</title>
18     
19     <meta http-equiv="pragma" content="no-cache">
20     <meta http-equiv="cache-control" content="no-cache">
21     <meta http-equiv="expires" content="0">    
22     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
23     <meta http-equiv="description" content="This is my page">
24     <!--
25     <link rel="stylesheet" type="text/css" href="styles.css">
26     -->
27 
28   </head>
29   
30   <body>
31     <h1>用户注册界面</h1>
32     <form action="RegisterServlet" method="post">
33         <table border="1">
34             <tr>
35                 <td>用户名:</td>
36                 <td><input type="text" name="username" size="30"></td>
37             </tr>
38             <tr>
39                 <td>密码:</td>
40                 <td><input type="password" name="password" size="30"></td>
41             </tr>
42             <tr>
43                 <td>验证邮箱:</td>
44                 <td><input type="text" name="email" size="30"></td>
45             </tr>
46             <tr>
47                 <td colspan="2" align="center"><input type="submit" value="提交"></td>
48             </tr>
49         </table>
50     </form>
51   </body>
52 </html>

 

2.创建User对象类User.java

 1 package com.mail.bean;
 2 
 3 /**
 4  * 
 5  * user的javabean实体类
 6  *
 7  */
 8 public class User {
 9     private Integer id;
10     private String username;
11     private String password;
12     private String email;
13     private Integer state;   
14     private String code;
15 
16     public Integer getId() {
17         return id;
18     }
19     public void setId(Integer id) {
20         this.id = id;
21     }
22     public String getUsername() {
23         return username;
24     }
25     public void setUsername(String username) {
26         this.username = username;
27     }
28     public String getPassword() {
29         return password;
30     }
31     public void setPassword(String password) {
32         this.password = password;
33     }
34     public String getEmail() {
35         return email;
36     }
37     public void setEmail(String email) {
38         this.email = email;
39     }
40     public Integer getState() {
41         return state;
42     }
43     public void setState(Integer state) {
44         this.state = state;
45     }
46     public String getCode() {
47         return code;
48     }
49     public void setCode(String code) {
50         this.code = code;
51     }
52 }

 

3. register.jsp提交过来的数据由RegisterServlet.java处理,而RegisterServlet.java只能调用业务层UserService.java接口

 1 package com.mail.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.mail.bean.User;
11 import com.mail.service.UserService;
12 import com.mail.service.UserServiceImpl;
13 import com.mail.utils.UUIDUtils;
14 
15 public class RegisterServlet extends HttpServlet {
16 
17     private static final long serialVersionUID = 1L;
18 
19     public void doGet(HttpServletRequest request, HttpServletResponse response)
20             throws ServletException, IOException {
21         
22         //接收表格传进来的数据
23         request.setCharacterEncoding("GB18030");   //设置编码
24         String username = request.getParameter("username");
25         String password = request.getParameter("password");
26         String email = request.getParameter("email");
27         
28         //数据封装
29         User user = new User();
30         user.setUsername(username);
31         user.setPassword(password);
32         user.setEmail(email);
33         user.setState(0);   //0:未激活     1:已激活
34         String code = UUIDUtils.getUUID();  //得到的编码去掉所有"-",剩32位
35         user.setCode(code);
36         
37         //调用业务层传递用户信息
38         UserService userService = new UserServiceImpl();
39         userService.register(user);
40         
41         //页面跳转
42         request.setAttribute("msg", "您已注册成功,请去邮箱激活!");
43         request.getRequestDispatcher("/msg.jsp").forward(request, response);
44     }
45 
46     public void doPost(HttpServletRequest request, HttpServletResponse response)
47             throws ServletException, IOException {
48         doGet(request, response);   //记得一定要调用这个
49     }
50 
51 }

 

4. UserService.java接口代码

 1 package com.mail.service;
 2 
 3 import com.mail.bean.User;
 4 
 5 public interface UserService {
 6 
 7     void register(User user);
 8 
 9     User foundByCode(String code);
10 
11     void update(User user);
12 
13 }

 

5.UserServiceImpl.java实现了UserService.java接口

 1 package com.mail.service;
 2 
 3 import javax.mail.MessagingException;
 4 import javax.mail.internet.AddressException;
 5 
 6 import com.mail.bean.User;
 7 import com.mail.dao.UserDAO;
 8 import com.mail.dao.UserDaoImpl;
 9 import com.mail.utils.MailUtils;
10 
11 public class UserServiceImpl implements UserService {
12 
13     @Override
14     public void register(User user) {
15         //向dao传递user
16         UserDAO userDAO = new UserDaoImpl();
17         userDAO.register(user);
18         
19         //给邮箱发送一封邮件
20         try {
21             MailUtils.senMail(user.getEmail(), user.getCode());  
22         } catch (AddressException e) {
23             e.printStackTrace();
24         } catch (MessagingException e) {
25             e.printStackTrace();
26         }
27     }
28 
29     @Override
30     public User foundByCode(String code) {
31         UserDAO userDAO = new UserDaoImpl();
32         return userDAO.foundByCode(code);
33     }
34 
35     @Override
36     public void update(User user) {
37         UserDAO userDAO = new UserDaoImpl();
38         userDAO.update(user);
39     }
40 }

 

6.UserServiceImpl.java调用数据层接口的接口类UserDAO.java

 1 package com.mail.dao;
 2 
 3 import com.mail.bean.User;
 4 
 5 public interface UserDAO {
 6 
 7     void register(User user);
 8 
 9     User foundByCode(String code);
10 
11     void update(User user);
12 
13 }

 

7.同样的UserDaoImpl.java为UserDAO.java的实现类,直接调用了数据库连接池

 1 package com.mail.dao;
 2 
 3 import java.sql.SQLException;
 4 
 5 import org.apache.commons.dbutils.QueryRunner;
 6 import org.apache.commons.dbutils.handlers.BeanHandler;
 7 
 8 import com.mail.bean.User;
 9 import com.mail.utils.JDBCUtils;
10 
11 public class UserDaoImpl implements UserDAO {
12 
13     @Override
14     public void register(User user) {
15         QueryRunner queryRunner = null;
16         try {
17             queryRunner = new QueryRunner(JDBCUtils.getDataSource());  //连接数据池
18             String sql = "insert into user values (?, ?, ?, ?, ?, ?)"; //插入数据
19             Object[] params = {user.getId(), user.getUsername(), user.getPassword(), user.getEmail(), user.getState(), user.getCode()};
20             queryRunner.update(sql, params);
21             } catch (SQLException e) {
22                 e.printStackTrace();
23             }  catch (Exception e) {
24                 e.printStackTrace();
25             }
26     }
27 
28     @Override
29     public User foundByCode(String code) {
30         QueryRunner queryRunner = null;
31         User user = null;
32         try {
33             queryRunner = new QueryRunner(JDBCUtils.getDataSource());
34             String sql = "select * from user where code = ?";
35             //BeanHandler<T>用于获取结果集中的第一行数据,并将其封装到JavaBean对象
36             user = queryRunner.query(sql, new BeanHandler<User>(User.class), code);
37         } catch (Exception e) {
38             e.printStackTrace();
39         }
40         return user;
41     }
42 
43     @Override
44     public void update(User user) {
45         QueryRunner queryRunner = null;
46         try {
47             queryRunner = new QueryRunner(JDBCUtils.getDataSource());
48             String sql = "update user set username=?, password=?, email=?, state=?, code=? where id=?";
49             Object[] params = {user.getUsername(), user.getPassword(), user.getEmail(), user.getState(), user.getCode(),user.getId()};
50             queryRunner.update(sql, params);52         } catch (Exception e) {
53             e.printStackTrace();
54         }
55     }
56 }

 

8.接着就是发送一封激活邮件给邮箱MailUtils.java

 1 package com.mail.utils;
 2 
 3 import java.util.Properties;
 4 
 5 import javax.mail.Message;
 6 import javax.mail.MessagingException;
 7 import javax.mail.Session;
 8 import javax.mail.Transport;
 9 import javax.mail.internet.AddressException;
10 import javax.mail.internet.InternetAddress;
11 import javax.mail.internet.MimeMessage;
12 import javax.mail.internet.MimeMessage.RecipientType;
13 
14 public class MailUtils {
15     public static void senMail(String toMail, String code) throws AddressException, MessagingException {
16         
17         Properties properties = new Properties();
18         properties.put("mail.transport.protocol", "smtp"); // 连接协议
19         properties.put("mail.smtp.host", "smtp.qq.com"); // 主机名
20         properties.put("mail.smtp.port", 465);  // 端口号
21         properties.put("mail.smtp.auth", "true");
22         properties.put("mail.smtp.ssl.enable", "true");  // 设置是否使用ssl安全连接 (一般都使用)
23         properties.put("mail.debug", "true"); // 设置是否显示debug信息 true 会在控制台显示相关信息
24         // 得到回话对象
25         Session session = Session.getInstance(properties);
26         // 获取邮件对象
27         Message message = new MimeMessage(session);
28         // 设置发件人邮箱地址
29         message.setFrom(new InternetAddress("系统邮箱@qq.com"));
30         // 设置收件人地址 
31         message.setRecipients( RecipientType.TO, new InternetAddress[] { new InternetAddress(toMail) });
32         // 设置邮件标题
33         message.setSubject("由JavaMail发出的测试邮件");
34         // 设置邮件内容
35         message.setContent("<h1>请点击以下链接址激活注册:</br><h3>(若无法点击,请复制到浏览器中打开)</h3></h1><h3><a herf='http://localhost:8080/MailTest/ActiveServlet?code="+code+"'>http://localhost:8080/MailTest/ActiveServlet?code="+code+"</a></h3>","text/html;Charset=UTF-8");
36         // 得到邮差对象
37         Transport transport = session.getTransport();
38         // 连接自己的邮箱账户
39         transport.connect("系统邮箱@qq.com", "cnqhvvkhqnzzbgce"); //密码为刚才得到的授权码
40         // 发送邮件 
41         transport.sendMessage(message, message.getAllRecipients());
42     }
43 }

 

9.响应激活邮箱的servlet类ActiveServlet.java

 1 package com.mail.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.mail.bean.User;
11 import com.mail.service.UserService;
12 import com.mail.service.UserServiceImpl;
13 
14 public class ActiveServlet extends HttpServlet {
15 
16     private static final long serialVersionUID = 1L;
17 
18     public void doGet(HttpServletRequest request, HttpServletResponse response)
19             throws ServletException, IOException {
20         //接受邮箱链接的激活码
21         String code = request.getParameter("code");
22         
23         //根据激活码查找到用户
24         UserService userService = new UserServiceImpl();
25         User user = userService.foundByCode(code);
26         if (user != null) {
27             user.setState(1);
28             user.setCode(null);
29             userService.update(user);
30             request.setAttribute("msg", "您已激活成功,请去登陆!");
31         }else {
32             //没有查到该用户
33             request.setAttribute("msg", "您的激活码有误,请点击链接重新激活!");
34         }
35         
36         //跳转至指定页面
37         request.getRequestDispatcher("/msg.jsp").forward(request, response);
38     }
39 
40     public void doPost(HttpServletRequest request, HttpServletResponse response)
41             throws ServletException, IOException {
42         doGet(request, response);
43     }
44 
45 }

 

10. msg.jsp代码

 1 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'msg.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26     <h1> ${ msg } </h1>
27   </body>
28 </html>

 

11.生成激活码的代码

 1 package com.mail.utils;
 2 
 3 /**
 4  * 用UUID随机产生字符串,用于激活码code
 5  */
 6 
 7 import java.util.UUID;
 8 
 9 public class UUIDUtils {
10     public static String getUUID() {
11         return UUID.randomUUID().toString().replaceAll("-", "");
12     }
13 }

 

12.Servlet的.xml配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="3.0"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 6   <servlet>
 7     <description>My First Servlet</description>
 8     <display-name>HelloServle</display-name>
 9     <servlet-name>RegisterServlet</servlet-name>
10     <servlet-class>com.mail.servlet.RegisterServlet</servlet-class>
11   </servlet>
12   <servlet>
13     <description>My First Servlet</description>
14     <display-name>HelloServle</display-name>
15     <servlet-name>ActiveServlet</servlet-name>
16     <servlet-class>com.mail.servlet.ActiveServlet</servlet-class>
17   </servlet>
18 
19 
20   <servlet-mapping>
21     <servlet-name>RegisterServlet</servlet-name>
22     <url-pattern>/RegisterServlet</url-pattern>
23   </servlet-mapping>
24   <servlet-mapping>
25     <servlet-name>ActiveServlet</servlet-name>
26     <url-pattern>/ActiveServlet</url-pattern>
27   </servlet-mapping>
28 
29 </web-app>

 

五 完成

  以上为全部代码内容,一定主要XML的文件配置以及JAR导入不要出错,根据部分人JDK环境的不同,可能还需要activation.jar和mail.jar两个包,在试用以上代码的时候一定要注意每一层的调用关系,有些地方需要自己修改的要注意(比如数据库的登陆密码,自己设置的系统邮箱,已经授权码等),要是看完之后发现有错误的地方或者又不理解的地方,请给我留言。最后祝大家开心度过每一天!o(* ̄▽ ̄*)ブ