2

I am trying to read mails from my GoDaddy mail box into my java program but I am facing error saying PKIX path building failed. I tried the solution shown on this link : "PKIX path building failed" and "unable to find valid certification path to requested target" . But still the error persists.Is there anything I should include in my java code.

My code:

    import java.util.concurrent.TimeUnit;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    import java.util.Properties;
    import javax.mail.BodyPart;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.internet.MimeMultipart;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.ScheduledFuture;

    public class WorkingProgram {

        public void poll() {
            final ScheduledExecutorService scheduler = Executors
                    .newScheduledThreadPool(1);
             final Properties props = new Properties();
            ScheduledFuture<?> files = scheduler.scheduleAtFixedRate(
                    new Runnable() {
                        public void run() { 
                            try{

                                String maxDate = null;
                                Class.forName("com.mysql.jdbc.Driver");
                                Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/emailproject","root","root");
                                Statement stmt=con.createStatement();  

                                ResultSet rs=stmt.executeQuery("SELECT DATE_FORMAT(MAX(received_date),'%Y-%m-%d %H:%i:%s') FROM emailproject.email_datetime_records e");
                                if(rs.next()){
                                    maxDate=rs.getString(1);
                                }
                                System.out.println(maxDate);
                                //con.close();

                                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
                                Date Dbdate = format.parse(maxDate);


                                 props.load(new FileInputStream(new File("E:\\PGFiltersWorkspace\\EmailParsing\\smtp.properties.txt")));
                                    Session session = Session.getDefaultInstance(props, null);
                                    Store store = session.getStore("imaps");
                                    store.connect("imap.secureserver.net", "**", "**");
                                    Folder inbox = store.getFolder("inbox");
                                    inbox.open(Folder.READ_ONLY);
                                    int messageCount = inbox.getMessageCount();
                                    Message[] messages = inbox.getMessages();
                                    for (int i = messageCount-1; i >=0; i--) 
                                    {
                                        if(Dbdate.compareTo(messages[i].getReceivedDate())<0){

                                        String result = "";

                                        if (messages[i].isMimeType("text/plain")) {
                                            result = messages[i].getContent().toString();
                                        } else if (messages[i].isMimeType("multipart/*")) {
                                            MimeMultipart mimeMultipart = (MimeMultipart) messages[i].getContent();
                                            result = getTextFromMimeMultipart(mimeMultipart);
                                        }
                                        System.out.println("Result is:"+result);

}
                                    else{

                                        break;
                                    }
                            }

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

                    }
                }, 0, 1, TimeUnit.MINUTES);
    }
    public static void main(String[] args) {

        WorkingProgram b = new WorkingProgram();
        b.poll();
    }
    private String getTextFromMimeMultipart(
            MimeMultipart mimeMultipart)  throws MessagingException, IOException{
        String result = "";
        int count = mimeMultipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            if (bodyPart.isMimeType("text/plain")) {
                result = result + "\n" + bodyPart.getContent();
                break; // without break same text appears twice in my tests
            } else if (bodyPart.isMimeType("text/html")) {
                String html = (String) bodyPart.getContent();
                result = result + "\n" + org.jsoup.Jsoup.parse(html).text();
            } else if (bodyPart.getContent() instanceof MimeMultipart){
                result = result + getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
            }
        }
        return result;
    }

}

The error is here:

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:295)
    at javax.mail.Service.connect(Service.java:176)
    at WorkingProgram$1.run(WorkingProgram.java:55)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source)
    at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
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(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
    at com.sun.mail.iap.Protocol.<init>(Protocol.java:113)
    at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:111)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:637)
    ... 11 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(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 25 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 31 more

The smtp.properties.txt is here:

mail.smtp.host=smtpout.secureserver.net
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.auth=true
mail.smtp.port=465

1 Answers1

0

Get rid of the socket factory settings, you don't need them.

For that matter, I don't see that you're using the properties file anywhere in your application, or even doing anything with smtp, so you can just remove the file.

Then follow these instructions in the JavaMail FAQ.

If you can't figure out how to install the certificate, set this property to ignore the certificate (note that this is a security risk):

mail.imaps.ssl.trust=imap.secureserver.net

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
  • This solution solved the PKIX build path error. But now I receive a new error for the same code above saying **A2 NO Mailbox does not exist.**. Any idea about this one? – krishna bharadia Jan 22 '18 at 04:45
  • Are you trying to access the "inbox" folder? It would be very unusual for it not to exist. What does the [JavaMail debug output](https://javaee.github.io/javamail/FAQ#debug) show? – Bill Shannon Jan 22 '18 at 21:57
  • Yes Sir. I am trying to access the inbox folder. It just gives me the error I mentioned above. – krishna bharadia Jan 23 '18 at 05:33
  • Do I have to ask again? What does the JavaMail debug output show? – Bill Shannon Jan 23 '18 at 07:21