title: javax.mail.MessagingException: Connect failed
body: <p>I am trying to read unread emails using Java program.I am using below mentioned java code which I took from <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm" rel="nofollow noreferrer">https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm</a>. I have turned on less secure apps access in gmail settings. Please help me to resolve the issue.</p>
  
  <pre><code>public class FetchingEmail {
  
     public static void fetch(String pop3Host, String storeType, String user,
        String password) {
        try {
           Properties properties = new Properties();
           properties.put("mail.store.protocol", "pop3");
           properties.put("mail.pop3.host", pop3Host);
           properties.put("mail.pop3.port", "995");
           properties.put("mail.pop3.starttls.enable", "*");
           Session emailSession = Session.getDefaultInstance(properties);
           Store store = emailSession.getStore("pop3s");
  
           store.connect(pop3Host, user, password);
           Folder emailFolder = store.getFolder("INBOX");
           emailFolder.open(Folder.READ_ONLY);
  
           BufferedReader reader = new BufferedReader(new InputStreamReader(
            System.in));
           Message[] messages = emailFolder.getMessages();
           System.out.println("messages.length---" + messages.length);
  
           for (int i = 0; i &lt; messages.length; i++) {
              Message message = messages[i];
              System.out.println("---------------------------------");
              writePart(message);
              String line = reader.readLine();
              if ("YES".equals(line)) {
                 message.writeTo(System.out);
              } else if ("QUIT".equals(line)) {
                 break;
              }
           }
           emailFolder.close(false);
           store.close();
  
        } catch (NoSuchProviderException e) {
           e.printStackTrace();
        } catch (MessagingException e) {
           e.printStackTrace();
        } catch (IOException e) {
           e.printStackTrace();
        } catch (Exception e) {
           e.printStackTrace();
        }
     }
     public static void main(String[] args) {
  
        String host = "pop.gmail.com";// change accordingly
        String mailStoreType = "pop3";
        String username = "abc@gmail.com";
           //"abc@gmail.com";// change accordingly
        String password = "abc";// change accordingly
        fetch(host, mailStoreType, username, password);
  
     }
     public static void writePart(Part p) throws Exception {
        if (p instanceof Message)
           writeEnvelope((Message) p);
  
        System.out.println("----------------------------");
        System.out.println("CONTENT-TYPE: " + p.getContentType());
        if (p.isMimeType("text/plain")) {
           System.out.println("This is plain text");
           System.out.println("---------------------------");
           System.out.println((String) p.getContent());
        }
        else if (p.isMimeType("multipart/*")) {
           System.out.println("This is a Multipart");
           System.out.println("---------------------------");
           Multipart mp = (Multipart) p.getContent();
           int count = mp.getCount();
           for (int i = 0; i &lt; count; i++)
              writePart(mp.getBodyPart(i));
        }
        else if (p.isMimeType("message/rfc822")) {
           System.out.println("This is a Nested Message");
           System.out.println("---------------------------");
           writePart((Part) p.getContent());
        }       
        else if (p.getContentType().contains("image/")) {
           System.out.println("content type" + p.getContentType());
           File f = new File("image" + new Date().getTime() + ".jpg");
           DataOutputStream output = new DataOutputStream(
              new BufferedOutputStream(new FileOutputStream(f)));
              com.sun.mail.util.BASE64DecoderStream test = 
                   (com.sun.mail.util.BASE64DecoderStream) p
                    .getContent();
           byte[] buffer = new byte[1024];
           int bytesRead;
           while ((bytesRead = test.read(buffer)) != -1) {
              output.write(buffer, 0, bytesRead);
           }
        } 
        else {
           Object o = p.getContent();
           if (o instanceof String) {
              System.out.println("This is a string");
              System.out.println("---------------------------");
              System.out.println((String) o);
           } 
           else if (o instanceof InputStream) {
              System.out.println("This is just an input stream");
              System.out.println("---------------------------");
              InputStream is = (InputStream) o;
              is = (InputStream) o;
              int c;
              while ((c = is.read()) != -1)
                 System.out.write(c);
           } 
           else {
              System.out.println("This is an unknown type");
              System.out.println("---------------------------");
              System.out.println(o.toString());
           }
        }
  
     }
     public static void writeEnvelope(Message m) throws Exception {
        System.out.println("This is the message envelope");
        System.out.println("---------------------------");
        Address[] a;
        if ((a = m.getFrom()) != null) {
           for (int j = 0; j &lt; a.length; j++)
           System.out.println("FROM: " + a[j].toString());
        }
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
           for (int j = 0; j &lt; a.length; j++)
           System.out.println("TO: " + a[j].toString());
        }
        if (m.getSubject() != null)
           System.out.println("SUBJECT: " + m.getSubject());
  
     }
  
  }
  </code></pre>
  
  <p>But I am getting below exception. I have posted stack trace.</p>
  
  <pre><code>javax.mail.MessagingException: Connect failed;
    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.pop3.POP3Store.protocolConnect(POP3Store.java:213)
      at javax.mail.Service.connect(Service.java:366)
      at javax.mail.Service.connect(Service.java:246)
      at com.util.FetchingEmail.fetch(FetchingEmail.java:62)
      at com.util.FetchingEmail.main(FetchingEmail.java:110)
  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:1964)
      at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:328)
      at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:322)
      at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1614)
      at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
      at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1052)
      at sun.security.ssl.Handshaker.process_record(Handshaker.java:987)
      at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1072)
      at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
      at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
      at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
      at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:598)
      at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:372)
      at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
      at com.sun.mail.pop3.Protocol.&lt;init&gt;(Protocol.java:112)
      at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:265)
      at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:207)
      ... 4 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:397)
      at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:302)
      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)
      at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
      at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1596)
      ... 17 more
  Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
      at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
      at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
      at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392)
  </code></pre>