javamail发qq邮件注册账户


参考文章:http://www.jb51.net/article/78405.htm
本程序是基于上文的改进完成。
开发及运行环境:eclipse jdk1.7 tomcat7
本程序以实现最基本功能为主,所用知识很基础,理解后可自行完善。
程序源码:https://github.com/2016lkaust/javamail


实现思路

javamail发qq邮件注册账户_第1张图片
实现思路

准备工作

  • 开启SMTP服务
    在 QQ 邮箱里的 设置->账户里开启 SMTP 服务
javamail发qq邮件注册账户_第2张图片
Paste_Image.png
  • 注意开启完之后,QQ 邮箱会生成一个授权码,在代码里连接邮箱使用这个授权码而不是原始的邮箱密码,这样可以避免使用明文密码。也可以使用明文密码,但是会有密码泄露的风险。(借用原作者的图吧,省的再截图)

    这里的授权码先记下来,第4步要用到。
    javamail发qq邮件注册账户_第3张图片
    Paste_Image.png

程序结构

javamail发qq邮件注册账户_第4张图片
程序结构

实现步骤

  • 1、 建数据库、表
  • 2、 User类(实体类)
  • 3、 UserDao类(与数据库交互)
  • 4、 SendMailUtils类(发送邮件)
  • 5、 UUIDUtils(生成随机字符串code)
  • 6、 RegistServlet(注册账户)
  • 7、 ActiveServlet(激活账户)
  • 8、 index.jsp(输入界面)
  • 9、 success.jsp(成功界面)

具体实现

1、 建数据库、表

/*
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(30) NOT NULL,
  `nickname` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL,
  `state` int(11) DEFAULT '0',
  `code` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、 User类(实体类)

package com.look.bean;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String nickname;//昵称
    private String email;
    private Integer state;//状态
    private String code;//随机码
    getter and setter...
}

3、 UserDao类(与数据库交互)

package com.look.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.look.bean.User;
public class UserDao {
    private static Connection conn;
    // 获取数据库连接
    public  void getConn() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/javamail";
            String rootname = "root";
            String rootpass = "123456";
            conn = DriverManager.getConnection(url, rootname, rootpass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // 注册
    public void regist(User user) {
        try {
            String sql = "insert into user(username,password,nickname,email,code) values(?,?,?,?,?)";
            PreparedStatement pstmt;
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getNickname());
            pstmt.setString(4, user.getEmail());
            pstmt.setString(5, user.getCode());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // 激活
    public void activeByCode(String code) {
                //状态标志置为1,code置空
        String sql = "update user set state=1,code=null where code=?";
        PreparedStatement pstmt;
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, code);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // 关闭数据库连接
    public void closeConn() {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}


mysql的账号密码需要修改为自己的账号密码。

4、 SendMailUtils类(发送邮件)

package com.look.util;

import java.security.GeneralSecurityException;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
public class SendMailUtils {
    public static void sendMail(String to, String code)
            throws GeneralSecurityException, MessagingException {
        Properties props = new Properties();
        // 开启debug调试
        // props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        Session session = Session.getInstance(props);
        Message msg = new MimeMessage(session);
        msg.setSubject("本邮件用于测试");
        // send text to the mail
        // StringBuilder builder = new StringBuilder();
        // builder.append("点击测试listCategory1");
        // msg.setText(builder.toString());
        msg.setContent(
                "点我激活", "text/html;charset=UTF-8");
        msg.setFrom(new InternetAddress("[email protected]"));
        Transport transport = session.getTransport();
        transport.connect("smtp.qq.com", "[email protected]",
                "hsvsqhofljqtjgdi");
        transport.sendMessage(msg, new Address[] { new InternetAddress(to) });
        transport.close();
    }
}

注:
msg.setFrom(new InternetAddress("[email protected]"));transport.connect("smtp.qq.com", "[email protected]","hsvsqhofljqtjgdi");中的[email protected]需要替换为你自己的qq邮箱,hsvsqhofljqtjgdi要替换为自己的授权码

5、 UUIDUtils(生成随机字符串code)

package com.look.util;
import java.util.UUID;
public class UUIDUtils {
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "")
                + UUID.randomUUID().toString().replace("-", "");
    }
}

6、 RegistServlet(注册账户)

package com.look.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.GeneralSecurityException;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.look.bean.User;
import com.look.dao.UserDao;
import com.look.util.SendMailUtils;
import com.look.util.UUIDUtils;
public class RegistServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void init() throws ServletException {
        super.init();
    }
    public void service(HttpServletRequest request, HttpServletResponse response) {
        // 获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String email = request.getParameter("email");
        // 封装数据
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setEmail(email);
        user.setCode(UUIDUtils.getUUID());
        System.out.println(user.getEmail() + "\t" + user.getCode());
        // 注册
        UserDao dao = new UserDao();
        dao.getConn();
        dao.regist(user);
        dao.closeConn();
        // 发送邮件
        try {
            SendMailUtils.sendMail(email, user.getCode());
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            out.print("

邮件已经发送到" + user.getEmail() + "中,请登录邮箱点击链接完成验证

"); out.flush(); out.close(); } catch (GeneralSecurityException | MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void destroy() { super.destroy(); } }

7、 ActiveServlet(激活账户)

package com.look.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.look.dao.UserDao;
public class ActiveServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    public void init() throws ServletException {
        super.init();
    }
    public void service(HttpServletRequest request,
            HttpServletResponse response) {
        // 获取数据
        String code = request.getParameter("code");
        // 数据库判断对应code是否存在,(这里就不进行判断了,直接进行比对)state=1&code=null代表激活
        UserDao dao = new UserDao();
        dao.getConn();
        dao.activeByCode(code);
        dao.closeConn();
        // 重定向success.jsp
        try {
            request.getRequestDispatcher("success.jsp").forward(request,
                    response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void destroy() {
        super.destroy();
    }
}

8、 index.jsp(输入界面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


    

9、 success.jsp(成功界面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


 
  成功激活
 
 
  
 

10、web.xml



  javamail
  
    index.jsp
  
  
    RegistServlet
    com.look.servlet.RegistServlet
  
  
    RegistServlet
    /RegistServlet
  
  
    ActiveServlet
    com.look.servlet.ActiveServlet
  
  
    ActiveServlet
    /ActiveServlet
  

你可能感兴趣的:(javamail发qq邮件注册账户)