2017-07-19 31 views
0

我試圖發送郵件使用SMTP,它設置爲具有25,587個端口和TLS的默認SMTP服務器。 MS Exchange 2010.所有身份驗證數據都是正確的,因爲我可以通過郵件的Web界面登錄。下面的代碼不使用Gmail的SMTP服務器工作,但是當我用我自己的SMTP服務器,它拋出我的證書路徑錯誤:TLS SMTP郵件Java引發SSLHandShakeException

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:PKIX路徑建築失敗: sun.security.provider.certpath.SunCertPathBuilderException:無法找到 有效證明路徑請求的目標

public static void SendMailTLS(String to, String subject, String body) throws Exception{ 

    try { 
       java.util.Properties props = new java.util.Properties(); 
       props.put("mail.smtp.host", "sample"); 
       props.put("mail.smtp.port", "587"); 
       props.put("mail.smtp.starttls.enable", "true"); 
       props.put("mail.smtp.auth", "true"); 
       props.put("mail.smtp.connectiontimeout", "10000");  
       final String EmailUser = "sample"; 
       final String EmailPassword = "sample";  
       Session session = Session.getInstance(props, new javax.mail.Authenticator() { 
          protected PasswordAuthentication getPasswordAuthentication() { 
          return new PasswordAuthentication(
           EmailUser,EmailPassword); 
          } 
         }); session.setDebug(true);  
       InternetAddress fromAddress = new InternetAddress("sample", 
             "sample"); 
       InternetAddress toAddress = new InternetAddress("sample", 
             "sample"); 
       Message msg = new MimeMessage(session); 
       msg.setFrom(fromAddress); 
       msg.addRecipient(Message.RecipientType.TO,toAddress); 
       msg.setSubject(subject); 
       msg.setText(body);  
       Transport transport = session.getTransport("smtp"); 
       transport.connect(); 
       transport.sendMessage(msg, msg.getAllRecipients()); 
       } catch (MessagingException e) {e.printStackTrace();} 
    } 

難道我做錯了什麼?

回答

0

此錯誤消息意味着名爲「sample」(MS Exchange 2010服務器)的服務器正在使用您的Java運行時不受信任的證書。您可能正在使用自簽名證書。所以您需要使用keytool將此證書導入Java運行時證書存儲區。