天天看点

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("[email protected]", "邮箱授权码");
            }
        };
        //创建程序到邮件服务器的第一次对话
        Session session = Session.getInstance(props, auth);
        //控制台输出debug信息
        session.setDebug(true);

        // 2.创建一个Message,它相当于邮件内容
        //相当于获取信封
        Message message = new MimeMessage(session);
        //设置发送人
        message.setFrom(new InternetAddress("[email protected]"));
        //设置发送方式与接收者
        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邮箱首页,点击设置->账户

java mail邮箱验证

然后往下翻页,

java mail邮箱验证

把第一个“开启”,按照提示操作,最后会生成一个授权码,写入PasswordAuthentication(“邮箱账号”, “授权码”)就OK了,如果还有问题,把图中的第二个也开启,两个授权码不一样,但是都可以用。