如何从 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 以不接收存档邮件。
参见:Read Gmail messages on other email clients using POP - Gmail Help
我需要阅读来自 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 以不接收存档邮件。
参见:Read Gmail messages on other email clients using POP - Gmail Help