Getting mail from GMail into Java application using IMAP(使用 IMAP 从 GMail 获取邮件到 Java 应用程序)
问题描述
我想使用 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.
这篇关于使用 IMAP 从 GMail 获取邮件到 Java 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 IMAP 从 GMail 获取邮件到 Java 应用程序
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01