java mail邮箱验证

java mail邮箱验证

    常见的比如注册账号的时候需要邮箱来激活账号然后才能正常登陆。

1,整体思路

    整体可分为两部分功能,一是给注册的邮箱发送一封激活邮件,二是激活邮件中有一链接用来激活账号。
    发送邮件的功能比较简单,主要是对邮件进行配置,包括连接时的协议,权限验证,创建会话,邮件主题和内容,发送方和接收方等信息,最后发送即可。
    主要涉及的类有:
    Properties:设置协议,权限等;
    Session:用来创建会话,也就是程序到邮件服务器的第一次对话;
    Message:设置邮件内容,发送方和接收方等。
    激活账号的时候一般都会有一个激活码,这个激活码就是用户创建账号的时候给用户设置的一个属性值,当用户激活的时候我们再根据这个属性值去查询用户,同时把用户的另一个属性值比如”status”从”0”更新为”1”,然后在用户登录的时候不仅要验证用户名和密码,还要验证这个”status”的值是不是为”1”,这样才能正常登录。

2,mail功能编写

需要的jar包:mail.jar

public class MailUtils {
    //String email:用户用来激活的邮箱
    //String emailMsg:邮件内容
    public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException, GeneralSecurityException, UnsupportedEncodingException{
        // 1.创建一个程序与邮件服务器会话对象 Session
        Properties props = new Properties();
        //设置连接时的协议为"SMTP"
        props.setProperty("mail.transport.protocol", "SMTP");
        //主机,qq邮箱就是"smtp.qq.com",163邮箱就是"smtp.163.com"
        props.setProperty("mail.host", "smtp.qq.com");
        //开启权限验证
        props.setProperty("mail.smtp.auth", "true");
        //ssl加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.setProperty("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        // 创建验证器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("122918552@qq.com", "邮箱授权码");
            }
        };
        //创建程序到邮件服务器的第一次对话
        Session session = Session.getInstance(props, auth);
        //控制台输出debug信息
        session.setDebug(true);

        // 2.创建一个Message,它相当于邮件内容
        //相当于获取信封
        Message message = new MimeMessage(session);
        //设置发送人
        message.setFrom(new InternetAddress("122918552@qq.com"));
        //设置发送方式与接收者
        message.setRecipient(RecipientType.TO, new InternetAddress(email));
        //邮件主题
        message.setSubject("activateMail");
        //邮件内容
        message.setContent(emailMsg, "text/html;charset=utf-8");

        // 3.创建 Transport用来发送邮件
        Transport.send(message);
    }
}
3,jsp编写
<form action="${pageContext.request.contextPath}/regist" method="post">
    <input type="hidden" name="method" value="regist"/>
    <table align="center" width="30%">
        ...
        <tr>
            <td>邮箱</td>
            <td><input id="email_id" type="text" name="email"/> </td>
        </tr>
        <tr>
            <td align="center" >
            <button id="regist_id" type="submit">注册</button> </td>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <td><button id="cancle_id" type="button">取消</button> </td>
        </tr>
    </table>
</form>

    ”form”表单中有个一隐藏的”input”,我们可以根据隐藏域中的”name”属性去获取”value”,然后在后台判断这个”value”,去做对应的操作,其实就是对请求进行统一管理。

4,servlet编写

    ”servlet”中首先对请求类型进行判断,上边的隐藏域这时候就用到了,这里主要模拟一个激活码,实际当中这个激活码是在用户注册账号的时候生成的,比如用”UUID”随机生成一串字符作为激活码。

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        String method = request.getParameter("method");
        if("regist".equals(method)) {
            //注册操作
            regist(request, response);
        }else if("active".equals(method)) {
            //激活操作
            active(request, response);
        }
    }

    public void regist(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //这里是用户注册之后显示的页面
        request.getRequestDispatcher("registLater.jsp").forward(request, response);
        //获取用户输入的email
        String email = request.getParameter("email");
        //模拟一个激活码"1234"
        String activeCode = "1234";
        //设置邮件内容,注意链接中的"method"
        String emailMsg = "注册成功,请点击<a href='http://localhost:8080/emailActivate/regist?method=active&activeCode="
            +activeCode
            +"'>激活</a>,验证码是"
            +activeCode;
        System.out.println("正在发送邮件...");
        try {
            //发送邮件
            MailUtils.sendMail(email, emailMsg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        System.out.println("发送邮件成功");
    }

    public void active(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //从激活请求链接中获取"activeCode"
        String activeCode = request.getParameter("activeCode");
        if("1234".equals(activeCode)) {
            System.out.println("激活成功");
            //进入到激活成功的页面
            request.getRequestDispatcher("activeSuccess.jsp").forward(request, response);
        }
    }
5,常见问题
5.1
5.1.1,问题描述

530 Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28 javax.mail.AuthenticationFailedException: 530 Error: A secure connection is requiered(such as ssl).More information at http://service.mail.qq.com/cgi-bin/help?id=28

5.1.2,问题原因:

没有ssl加密

5.1.3,解决办法:
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.setProperty("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
5.2
5.2.1,问题描述

535 Error: 请使用授权码登录。详情请看: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
javax.mail.AuthenticationFailedException: 535 Error: ?????????¨?????????ê?é????: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

5.2.2,问题原因:

这个就很明显了,需要使用授权码登录(此处用的是QQ邮箱发送文件)

5.2.3,解决办法:

进入QQ邮箱首页,点击设置->账户
这里写图片描述
然后往下翻页,
这里写图片描述
把第一个“开启”,按照提示操作,最后会生成一个授权码,写入PasswordAuthentication(“邮箱账号”, “授权码”)就OK了,如果还有问题,把图中的第二个也开启,两个授权码不一样,但是都可以用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现邮箱验证注册可以分为以下步骤: 1. 在注册页面中,用户输入注册信息,包括邮箱地址和密码等。 2. 点击注册按钮后,服务器端生成一个随机的验证码,并将验证码和邮箱地址存储在数据库中。 3. 服务器端将验证码通过邮件发送给用户,用户收到邮件后将验证码输入到注册页面中。 4. 用户点击验证按钮,客户端将用户输入的邮箱地址和验证码发送到服务器端。 5. 服务器端从数据库中查询该邮箱地址对应的验证码是否正确,如果正确则将用户信息存储到数据库中。 以下是Java代码示例: 1. 生成验证码 ``` public static String generateVerificationCode() { int length = 6; String code = ""; for (int i = 0; i < length; i++) { int rand = (int) (Math.random() * 10); code += rand; } return code; } ``` 2. 发送邮件 ``` public static void sendEmail(String recipient, String code) { String subject = "邮箱验证"; String content = "您的验证码为:" + code + ",请在注册页面中输入此验证码以完成邮箱验证。"; String smtpHost = "smtp.xxx.com"; // 邮件服务器地址 String smtpPort = "25"; // 邮件服务器端口 String from = "xxx@xxx.com"; // 发件人邮箱地址 String username = "xxx"; // 发件人用户名 String password = "xxx"; // 发件人密码 Properties props = new Properties(); props.setProperty("mail.smtp.host", smtpHost); props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); message.setSubject(subject); message.setContent(content, "text/html;charset=UTF-8"); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } } ``` 3. 验证验证码 ``` public static boolean verifyCode(String email, String code) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; boolean result = false; try { conn = getConnection(); pstmt = conn.prepareStatement("SELECT * FROM verification_code WHERE email = ? AND code = ?"); pstmt.setString(1, email); pstmt.setString(2, code); rs = pstmt.executeQuery(); if (rs.next()) { result = true; } } catch (SQLException e) { e.printStackTrace(); } finally { close(conn, pstmt, rs); } return result; } ``` 4. 存储用户信息 ``` public static void saveUser(User user) { Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); pstmt = conn.prepareStatement("INSERT INTO user(email, password) VALUES (?, ?)"); pstmt.setString(1, user.getEmail()); pstmt.setString(2, user.getPassword()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { close(conn, pstmt, null); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值