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 应用程序
基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
