2010-06-17 63 views

回答

16

這個問題:'Verify mail server connection programmatically in ColdFusion'有一個Java解決方案作爲公認的答案的一部分:

int port = 587; 
String host = "smtp.gmail.com"; 
String user = "[email protected]"; 
String pwd = "email password"; 

try { 
    Properties props = new Properties(); 
    // required for gmail 
    props.put("mail.smtp.starttls.enable","true"); 
    props.put("mail.smtp.auth", "true"); 
    // or use getDefaultInstance instance if desired... 
    Session session = Session.getInstance(props, null); 
    Transport transport = session.getTransport("smtp"); 
    transport.connect(host, port, user, pwd); 
    transport.close(); 
    System.out.println("success"); 
} 
catch(AuthenticationFailedException e) { 
     System.out.println("AuthenticationFailedException - for authentication failures"); 
     e.printStackTrace(); 
} 
catch(MessagingException e) { 
     System.out.println("for other failures"); 
     e.printStackTrace(); 
} 
+0

我已經試過這一點,它不爲Gmail以外地址的工作 - 始終打印成功。任何想法爲什麼?我正在使用smtp.1and1.com和不正確的憑據仍然打印成功 – ntgCleaner 2016-02-10 15:47:15

+0

我試過你的解決方案,但即使使用正確的數據(我現在正在用這些電子郵件數據設置發送電子郵件)我得到: 535錯誤的驗證數據 任何想法? – 2016-05-18 21:06:34

5
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; 
} 
+1

Bak,我試過這個,但就像上面的答案一樣,當我不應該成爲成功信息時,我會收到一條成功信息。我在做什麼會有什麼問題? – ntgCleaner 2016-02-10 15:56:26

相關問題