Q:

javax.mail.MessagingException Is throwing when I try to connect via IMAP to Gmail

Trying to connect to gmail via IMAP connection, catch javax.mail.MessagingException
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;
    }
}

Stack Trace:

javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
    nested exception is:
      javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
      at javax.mail.Service.connect(Service.java:364)
      at javax.mail.Service.connect(Service.java:245)
      at insynctive.utils.MailManager.getEmailByBody(MailManager.java:39)
      at insynctive.utils.MailManager.getVerificationCode(MailManager.java:106)
      at insynctive.pages.insynctive.TwoFAPage.sendViaPrimaryEmail(TwoFAPage.java:49)
      at insynctive.tests.PersonFileTest.loginWith2FAEmail(PersonFileTest.java:148)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at 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)
      at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:845)
      at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1153)
      at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
      at org.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)
      at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
      at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
      at org.testng.SuiteRunner.run(SuiteRunner.java:259)
      at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
      at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
      at 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)
  Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      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)
      at sun.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)
      at sun.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)
      at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
      at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
      at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
      at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
      at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
      at com.sun.mail.iap.Protocol.(Protocol.java:116)
      at com.sun.mail.imap.protocol.IMAPProtocol.(IMAPProtocol.java:115)
      at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:685)
      at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636)
      ... 29 more
  Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
      at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
      at sun.security.validator.Validator.validate(Validator.java:260)
      at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
      at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)

Main: 
public static void main(String[] args) throws Exception {
        MailManager.getEmailByBody("asd@gmail.com", "password", "Hello");
}

A:

The problem was that Gmail block all external access, I resolved that problem cancelling all the gmail security in the account.

