javax.mail.MessagingException 尝试连接到 gmail IMAP 服务器时

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

我正在尝试通过 Gmail imap 协议连接到 Gmail 帐户

这是我调用的方法:

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);}

这是我得到的异常:

 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

我已经阅读并尝试过其他问题中发布的解决方案,但它们对我不起作用。我想我错过了什么

非常感谢您的帮助。谢谢。

session.getStore("imaps")是我平时不用的。相反,您会将协议作为属性的一部分。

我最好的猜测是您收到错误消息是因为您当时并没有真正连接到 google。

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();
}

经过 3 个小时的 tinkering/debugging 我终于解决了这个问题。结果是 avast 导致了这个 SSL 错误,禁用它使代码正常工作。