java mail实现smtp登录验证

官网API没有实例,研究了好一会才试出来,希望能帮到大家

/**
     * 邮箱验证(smtp)
     * @param account 邮箱地址
     * @param password  密码
     * @return  验证结果
     */
    public static String checkMailUserBySmtp(String account, String password) {
        try {
            Properties properties = new Properties();
            properties.put("mail.transport.protocol", "smtp");
            properties.put("mail.smtp.host", MAILHOST);
            properties.put("mail.smtp.port", MAILPORT_SMTP);
            properties.put("mail.smtp.auth", "true");
            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(account, password); // 发件人邮箱账号、授权码
                }
            });
            Transport transport = session.getTransport();
            transport.connect(account, password);
            transport.close();
            LogUtil.serviceLogger.info("denglu ok...........");
            return SysConfig.YES;
        } catch (NoSuchProviderException e) {
            LogUtil.serviceLogger.error(e, "邮箱登录-供应商没有提供服务");
        } catch (SendFailedException e) {
            LogUtil.serviceLogger.error(e,"邮箱登录-邮件发送错误");
        } catch (AuthenticationFailedException e) {
            if("EOF on socket".equals(e.getMessage())){//邮件服务器异常
                return SysConfig.NULL;
            }
            LogUtil.serviceLogger.error(e,"邮箱登录-用户名或密码错误");
        } catch (MessagingException e) {
            if (e.getCause() != null)  return SysConfig.NULL;
        } catch (Exception e) {
            LogUtil.serviceLogger.error(e, "邮箱登录失败");
        }
        return SysConfig.NO;
    }

版权声明:本文为lgd15991672574原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。