【问题标题】:How to read e-mails from inbox of a GMail account in Java?如何从 Java 中的 GMail 帐户的收件箱中读取电子邮件?
【发布时间】:2020-07-10 10:44:55
【问题描述】:

我需要阅读来自 Gmail 帐户的电子邮件。我写了以下代码:

public class ReadResponseToEmailTest {
    @Test
    public void testGmailConnection() throws MessagingException {
        Folder emailFolder = null;
        Store store = null;
        try {
            //create properties field
            Properties properties = new Properties();

            properties.put("mail.pop3.host", "pop.gmail.com");
            properties.put("mail.pop3.port", Integer.toString(995));
            properties.put("mail.pop3.starttls.enable", "true");

            Session emailSession = Session.getDefaultInstance(properties);

            //create the POP3 store object and connect with the pop server

            store = emailSession.getStore("pop3s");

            store.connect("pop.gmail.com", "myemail@gmail.com", "XXXXXXXX");

            //create the folder object and open it

            emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            // retrieve the messages from the folder in an array and print it
            Message foundMessage = null;
            Message[] messages = emailFolder.getMessages();
            for (final Message msg : messages) {
                final String subject = msg.getSubject();
            }
        }
        finally {
            if (emailFolder != null) {
                emailFolder.close(false);
            }
            if (store != null) {
                store.close();
            }
        }

    }
}

messages 仅包含旧消息。此外,这些邮件大部分不在收件箱中,而是存档。

我需要如何更改上述代码才能阅读 GMail 收件箱中的电子邮件(尤其是最近收到的电子邮件)?

【问题讨论】:

    标签: java email gmail jakarta-mail


    【解决方案1】:

    检查您的gmail 帐户设置:

    • 点击右上角的设置⚙⇒查看所有设置

    • 点击转发和 POP/IMAP 标签。

    • 所有邮件启用 POP(甚至是已经下载的邮件)

    • 还可以尝试检查第二个单选按钮:为从现在开始到达的邮件启用 POP,以不接收归档邮件。

    见:Read Gmail messages on other email clients using POP - Gmail Help

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2019-10-24
      • 1970-01-01
      • 2014-05-19
      • 2017-05-15
      • 2015-03-13
      • 2013-11-17
      相关资源
      最近更新 更多