2015-11-15 2 views
0

Попытка подключения к GMAIL через соединение по протоколу IMAP, пойматьjavax.mail.MessagingExceptionjavax.mail.MessagingException бросает, когда я пытаюсь подключиться через IMAP в Gmail

public static StringBuffer getEmailByBody(String username, String password, String containsMsg) throws Exception { 
    Properties props = System.getProperties(); 
    props.setProperty("mail.store.protocol", "imaps"); 
    props.setProperty("mail.imap.ssl.enable", "true"); 

    Session session = Session.getDefaultInstance(props, null); 
    Store store = session.getStore("imaps"); 
    try { 
     store.connect("imap.gmail.com", username , password); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
     throw new Exception("Fail in connection" + ex.getMessage()); 
    } 

    Folder folder = store.getFolder("INBOX"); 
    folder.open(Folder.READ_WRITE); 

    Message[] messages = null; 
    boolean isMailFound = false; 
    Message confirmationMAil = null; 

    // Search for mail MAX 10 runs 
    for (int i = 0; i < 10; i++) { 
     messages = folder.search(new BodyTerm(containsMsg), folder.getMessages()); 
     for(Message message : messages){ 
      if (!message.isSet(Flags.Flag.SEEN)) { 
       confirmationMAil = message; 
       isMailFound = true; 
       break; 
      } 
     } 
     // wait for 3 seconds if message is not found 
     if (!isMailFound) { 
      Thread.sleep(3000); 
     } 
    } 

    // Search latests for unread mail 
    for(Message message : messages){ 
     if (!message.isSet(Flags.Flag.SEEN)) { 
      confirmationMAil = message; 
      isMailFound = true; 
      break; 
     } 
    } 

    // Test fails if no unread mail was found from God 
    if (!isMailFound) { 
     throw new Exception("Could not find email"); 

     // Read the content of mail and launch registration URL 
    } else { 
     String line; 
     StringBuffer buffer = new StringBuffer(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       confirmationMAil.getInputStream())); 
     while ((line = reader.readLine()) != null) { 
      buffer.append(line); 
     } 
     return buffer; 
    } 
} 

трассировки стека:

javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX путь здание не удалось: sun.security.provider.certpath.SunCertPathBuilderException: не удалось найти допустимый путь сертификации для запрошенной цели; Вложенное исключение: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: Не удалось создать путь PKIX: sun.security.provider.certpath.SunCertPathBuilderException: не удалось найти действительный путь сертификации для запрошенной цели at com. sun.mail.imap.IMAPStore.protocolConnect (IMAPStore.java:670) в javax.mail.Service.connect (Service.java:364) at javax.mail.Service.connect (Service.java:245) at insynctive.utils.MailManager.getEmailByBody (MailManager.java:39) на insynctive.utils.MailManager.getVerificationCode (MailManager.java:106) на insynctive.pages.insynctive.TwoFAPage.sendViaPrimaryEmail (TwoFAPage.java:49) на insynctive.tests.PersonFileTest.loginWith2FAEmail (PersonFileTest.ja ва: 148) на sun.reflect.NativeMethodAccessorImpl.invoke0 (нативный метод) на sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) на sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) в java.lang.reflect.Method.invoke (Method.java:483) at org.testng.internal.MethodInvocationHelper.invokeMethod (MethodInvocationHelper.java:85) at org.testng.internal.Invoker.invokeMethod (Invoker.java : 659) в org.testng.internal.Invoker.invokeTestMethod (Invoker.java:845) на org.testng.internal.Invoker.invokeTestMethods (Invoker.java:1153) в org.testng.internal.TestMethodWorker.invokeTestMethods (TestMethodWorker.java:125) на или g.testng.internal.TestMethodWorker.run (TestMethodWorker.java:108) at org.testng.TestRunner.privateRun (TestRunner.java:771) at org.testng.TestRunner.run (TestRunner.java:621) at org.testng.SuiteRunner.runTest (SuiteRunner.java:357) на org.testng.SuiteRunner.runSequentially (SuiteRunner.java:352) на org.testng.SuiteRunner.privateRun (SuiteRunner.java:310) at org. testng.SuiteRunner.run (SuiteRunner.java:259) на org.testng.SuiteRunnerWorker.runSuite (SuiteRunnerWorker.java:52) на org.testng.SuiteRunnerWorker.run (SuiteRunnerWorker.java:86) на org.testng. TestNG.runSuitesSequentially (TestNG.java:1199) at org.testng.TestNG.runSuitesLocally (TestNG.java:1124) at org.testng.TestNG.run (TestNG.java:1032) at insynctive.runnable.RunnableTest.run (RunnableTest.java:36) at java.lang.Thread.run (Thread.java:745) Причиненный by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: Не удалось создать путь PKIX: sun.security.provider.certpath.SunCertPathBuilderException: не удалось найти допустимый путь сертификации для запрошенной цели at sun.security.ssl. Alerts.getSSLException (Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal (SSLSocketImpl.java:1917) at sun.security.ssl.Handshaker.fatalSE (Handshaker.java:301) на солнце. security.ssl.Handshaker.fatalSE (Handshaker.java:295) at sun.security.ssl.ClientHandshaker.serverCertificate (ClientHandshaker.java:1369) at sun.security.ssl.ClientHandshaker.processMessage (ClientHandshaker.java:156) at sun.security.ssl.Handshaker.processLoop (Handshaker.java:925) на солнце. security.ssl.Handshaker.process_record (Handshaker.java:860) at sun.security.ssl.SSLSocketImpl.readRecord (SSLSocketImpl.java:1043) at sun.security.ssl.SSLSocketImpl.performInitialHandshake (SSLSocketImpl.java:1343) на sun.security.ssl.SSLSocketImpl.startHandshake (SSLSocketImpl.java:1371) в sun.security.ssl.SSLSocketImpl.startHandshake (SSLSocketImpl.java:1355) в com.sun.mail.util.SocketFetcher.configureSSLSocket (SocketFetcher.java:549) at com.sun.mail.util.SocketFetcher.createSocket (Soc ketFetcher.java:354) на com.sun.mail.util.SocketFetcher.getSocket (SocketFetcher.java:237) на com.sun.mail.iap.Protocol. (Protocol.java:116) на com.sun .mail.imap.protocol.IMAPProtocol. (IMAPProtocol.java:115) по адресу com.sun.mail.imap.IMAPStore.newIMAPProtocol (IMAPStore.java:685) по адресу com.sun.mail.imap.IMAPStore.protocolConnect (IMAPStore.java:636) ... 29 еще Вызвано: sun.security.validator.ValidatorException: Не удалось создать путь PKIX: sun.security.provider.certpath.SunCertPathBuilderException: не удалось найти допустимый путь сертификации для запрошенной цели at sun.security.validator.PKIXValidator.doBuild (PKIXValidator.java:387) at sun.security.validator.PKIXValidator.engineValidate (PKIXValidator.java:292) на sun.security.validator.Validator.validate (Validator.java:260) в sun.security.ssl.X509TrustManagerImpl.validate (X509TrustManagerImpl.java:324) в sun.security.ssl.X509TrustManagerImpl.checkTrusted (X509TrustManagerImpl. Java: 229)

Главная:

public static void main(String[] args) throws Exception { 
     MailManager.getEmailByBody("[email protected]", "password", "Hello"); 
} 
+0

Это [JavaMail запись FAQ] (http://www.oracle.com/technetwork/java/javamail/faq/index.html#installcert) может помочь. –

+0

Не удалось решить –

+0

Подробнее, пожалуйста. Что именно вы пробовали? Каковы были результаты? Где работает ваша Java-программа? На сервере приложений? Как самостоятельная программа? –

ответ

0

проблема заключалась в том, что блок Gmail весь внешний доступ, я решил, что проблема отменяет всю безопасность gmail в учетной записи.

0

Попробуйте добавить эту строку кода prop.put("mail.imap.ssl.trust", "*");

+0

Не могли бы вы быть более сложными и объяснить, куда вводить эту линию, и почему это было бы решением? – trincot

0

Попробуйте добавить это, прежде чем называть класс Session:

System.setProperty("javax.net.ssl.trustStore", path to your cacerts file in your Java folder, inside your hard disk); 
     System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); 
     Properties prop = new Properties(); 
     prop.setProperty("mail.pop3.starttls.enable", "false"); 
     prop.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
     prop.setProperty("mail.pop3.socketFactory.fallback", "false"); 
     prop.setProperty("mail.pop3.port", port); 
     prop.setProperty("mail.pop3.socketFactory.port", port); 
     prop.setProperty("mail.imap.ssl.trust", "*"); 
     MailSSLSocketFactory sf = new MailSSLSocketFactory(); 
     sf.setTrustAllHosts(true); 
     prop.put("mail.smtp.ssl.socketFactory", sf); 
Смежные вопросы