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

Viewed 276

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 = "realemail@gmail.com";
        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.

2 Answers

The session.getStore("imaps") is something I usually don't use. Instead, you'd give the protocol as part of the properties.

My best guess is that you receive the error as you're not really being connected to google at that point.

Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imaps.ssl.enable", "true");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.timeout", "10000");
props.setProperty("mail.imaps.connectiontimeout", "10000");

try {

    Session session = Session.getInstance(props, null);
    Store store = session.getStore();
    store.connect("imap.gmail.com", user, password);
    Folder inbox = store.getFolder("INBOX");

    System.out.println("Connected!");

} catch(Exception e) {
  e.printStackTrace();
}

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.

Related