Validate smtp server credentials using java without actually sending mail

前端 未结 2 715
我在风中等你
我在风中等你 2020-12-17 00:36

To verify smtp server credentials shall I use transport.connect()?

Session session = Session.getInstance(properties,authenticator);

 Transport          


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 00:45

    public boolean confirmSMTP(String host, String port, String username, String password, String auth, String enctype) {
        boolean result = false;
        try {
            Properties props = new Properties();
            if (auth.equals(true)) {
                props.setProperty("mail.smtp.auth", "true"); 
            } else { 
                props.setProperty("mail.smtp.auth", "false"); 
            }
            if (enctype.endsWith("TLS")) {
                props.setProperty("mail.smtp.starttls.enable", "true");
            } else if (enctype.endsWith("SSL")) {
                props.setProperty("mail.smtp.startssl.enable", "true");
            }
            Session session = Session.getInstance(props, null);
            Transport transport = session.getTransport("smtp");
            int portint = Integer.parseInt(port);
            transport.connect(host, portint, username, password);
            transport.close();
            result = true;
    
        } catch(AuthenticationFailedException e) {
            Logging.addMsg(e.toString(), "SMTP: Authentication Failed", false, true);
    
        } catch(MessagingException e) {
            Logging.addMsg(e.toString(), "SMTP: Messaging Exception Occurred", false, true);
        } catch (Exception e) {
            Logging.addMsg(e.toString(), "SMTP: Unknown Exception", false, true);
        }
    
        return result;
    }
    

提交回复
热议问题