Search code examples
javaemailsmtpjakarta-mailimap

javax.mail.MessagingException when attempting to connect to gmail IMAP server


I am trying to connect to a gmail account via Gmail imap protocol

Here is the method I am calling:

public EmailHelper() throws MessagingException, GeneralSecurityException {

        String username = "[email protected]";
        String password = "emailpassword";
        String server = "imap.gmail.com";

        Properties props = System.getProperties();
        props.setProperty("mail.imap.ssl.enable", "true");
        props.setProperty("mail.store.protocol", "imaps");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.imaps.ssl.checkserveridentity", "false");
        props.put("mail.imaps.ssl.trust", "*");
        props.put("mail.imaps.ssl.socketFactory", sf);

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");


        store.connect(server, username, password);}

This is the exception I get:

 Exception in thread "main" 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

I have read and attempted solutions posted in other questions yet they didn't work for me. I think I am missing something

Assistance would be highly appreciated. Thank you.


Solution

  • I finally resolved the issue after 3 hours of tinkering/debugging. It turns out avast was causing this SSL error, and disabling it made the code work.