java邮件验证

实现流程

-用户注册
-服务端发送邮件给用户客户端
-用户点击邮件中的链接
-服务端确认验证成功

JavaMail

提供给开发者处理相关的编程接口。它是Sun发布的用来处理mail的API,它可以方便的执行一些邮件传输。

邮箱术语

电子邮箱:用户在邮件服务器上申请账户,邮箱服务器会为这个用户分配一定的空间,用户从而可以使用这个账户的空间进行收发邮件。
邮件服务器:一台安装了邮件服务软件的电脑。
邮件发送协议(SMTP):Simple Mail Transfer Protocol简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由他来控制邮件的中转方式,属于TCP/IP协议簇。通常把处理用户SMTP请求的邮件服务器称为SMTP服务器。
POP3协议:Post Office Protocol - version3邮局协议版本3。支持客户端远程管理在服务器上的邮件。通常把处理用户POP3请求的邮件服务器称为POP3服务器。

邮件收发过程

这里写图片描述

服务器环境

使用易邮邮箱服务器。在工具->邮箱服务器中设置邮箱域名。然后创建两个邮箱账号。这里写图片描述

使用foxmail收发邮件。注意如果要配置QQ邮箱,有一些设置比如接受服务器类型需要在网络客户端完成,具体不展开。

搭建开发环境

数据库准备

这里写图片描述

注册页面

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'regist.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
  <h1>用户注册界面</h1>
  <form action="${pageContext.request.contextPath}/RegistServlet" method="post">
      <table width="400" border="1">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="username"/></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password"/></td>
        </tr>
        <tr>
            <td>昵称</td>
            <td><input type="text" name="nickname"/></td>
        </tr>
        <tr>
            <td>邮箱</td>
            <td><input type="text" name="email"/></td>
        </tr>
        <tr>            
            <td colspan="2"><input type="submit" value="注册"/></td>
        </tr>
      </table>
  </form>
  </body>
</html>

邮箱工具类

首先要连接邮件服务器,然后创建邮件,最后发送。

/**
 * 邮件发送工具类
 * @author Sherry
 * 
 */
public class MailUtils {
    /**
     * 发送邮件的方法
     * 
     * @param to
     *            :发送目标
     * @param code
     *            :激活码
     * @throws
     * @throws Exception
     */
    public static void sendMail(String to, String code) throws Exception {
        // 创建连接对象,连接到邮件服务器
        Properties props = new Properties();// 可以用来设置主机或者邮件服务器信息等
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 专门用来发送激活邮件的邮箱
                return new PasswordAuthentication("service@store.com", "111");
            }
        });
        // 创建邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人
        message.setFrom(new InternetAddress("service@store.com"));
        // 设置收件人
        message.setRecipient(RecipientType.TO, new InternetAddress(to));
        // 设置主题
        message.setSubject("来自xx网站的邮件");
        // 设置邮件的正文
        message.setContent(
                "<h1>来自xx网站的邮件,激活请点击一下链接:</h1><h3><a href='http:///idea-pc:12345/regist_web/ActiveServlet?code="
                        + code
                        + "'>http:///idea-pc:12345/regist_web/ActiveServlet?code="
                        + code + "</a></h3>", "text/html;charset=UTF-8");
        // 发送邮件
        Transport.send(message);
    }
}

处理用户点击验证地址事件

用户在注册的时候,我们通过service@store.com给他发送了一封验证邮件,当用户点击这个超链接,要处理这个验证请求。这里是把用户在数据库中的状态做一个改变。当一个用户注册并且状态已激活时,才可以登录。

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 接受激活码
            String code = request.getParameter("code");
            // 根据激活码查询用户
            UserService service = new UserServiceImpl();
            User user = service.findByCode(code);
            if (user != null) {
                // 已经查询到,修改用户状态
                user.setState(1);
                user.setCode(null);
                service.update(user);
                request.setAttribute("msg", "您已激活成功,请登录!");
            } else {
                // 根据激活码没有查询到用户
                request.setAttribute("msg", "激活码有误,请重新激活!");
            }
            request.getRequestDispatcher("/msg.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

注意,注册和激活的servlet要在web.xml中注册。

github地址:https://github.com/myfwjy/regist_web

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值