使用 IMAP 从 GMail 获取邮件到 Java 应用程序

2022-01-23 00:00:00 imap gmail java jakarta-mail

我想使用 JavaMail 和 IMAP.为什么我会收到 SocketTimeoutException ?

I want to access messages in Gmail from a Java application using JavaMail and IMAP. Why am I getting a SocketTimeoutException ?

这是我的代码:

Properties props = System.getProperties();
props.setProperty("mail.imap.host", "imap.gmail.com");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.connectiontimeout", "5000");
props.setProperty("mail.imap.timeout", "5000");

try {
    Session session = Session.getDefaultInstance(props, new MyAuthenticator());
    URLName urlName = new URLName("imap://MYUSERNAME@gmail.com:MYPASSWORD@imap.gmail.com");
    Store store = session.getStore(urlName);
    if (!store.isConnected()) {
        store.connect();
    }
} catch (NoSuchProviderException e) {
    e.printStackTrace();
    System.exit(1);
} catch (MessagingException e) {
    e.printStackTrace();
    System.exit(2);
}

我已经设置了超时值,这样它就不会永远"超时.此外,MyAuthenticator 也有用户名和密码,这似乎与 URL 是多余的.还有另一种指定协议的方法吗?(我没有在 IMAP 的 JavaDoc 中看到它.)

I have set the timeout values so that it wouldn't take "forever" to timeout. Also, MyAuthenticator also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for IMAP.)

推荐答案

使用 imaps 是一个很好的建议.提供的答案都没有对我有用,所以我用谷歌搜索了更多,发现了一些有用的东西.这是我的代码现在的样子.

Using imaps was a great suggestion. Neither of the answers provided just worked for me, so I googled some more and found something that worked. Here's how my code looks now.

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
  Session session = Session.getDefaultInstance(props, null);
  Store store = session.getStore("imaps");
  store.connect("imap.gmail.com", "<username>@gmail.com", "<password>");
  ...
} catch (NoSuchProviderException e) {
  e.printStackTrace();
  System.exit(1);
} catch (MessagingException e) {
  e.printStackTrace();
  System.exit(2);
}

这很好,因为它消除了多余的 Authenticator.我很高兴这能奏效,因为 SSLNOTES.txt 让我头晕目眩.

This is nice because it takes the redundant Authenticator out of the picture. I'm glad this worked because the SSLNOTES.txt make my head spin.

相关文章