使用IMAP将GMail中的邮件转化为Java应用程序 [英] Getting mail from GMail into Java application using IMAP

查看:83
本文介绍了使用IMAP将GMail中的邮件转化为Java应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaMail和IMAP从Java应用程序访问GMail中的消息。为什么我得到一个 SocketTimeoutException

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

这是我的代码:

Here is my code:

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来说似乎是多余的。是否有另一种方式来指定协议? (我没有在JavaDoc for IMAP中看到它。)

I 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应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆