繁体   English   中英

如何从 Java 中的 GMail 帐户的收件箱中读取电子邮件?

[英]How to read e-mails from inbox of a GMail account in Java?

我需要阅读来自 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 收件箱中的电子邮件(尤其是最近收到的电子邮件)?

检查您的gmail帐户设置:

  • 在右上角,单击设置 ⚙ ⇒ 查看所有设置

  • 单击转发和 POP/IMAP选项卡。

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

在此处输入图像描述

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

请参阅:使用 POP 读取其他 email 客户端上的 Gmail 消息 - Gmail 帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM