java 收 特定日期邮件_java mail解析邮件并获取最近时间的指定邮件
时间: 2024-01-27 11:06:19 浏览: 19
以下是使用 JavaMail 解析邮件并获取最近时间的指定邮件的示例代码:
```
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailParser {
public static void main(String[] args) throws Exception {
String host = "your-hostname";
String username = "your-username";
String password = "your-password";
// Set properties for IMAP server
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imaps.host", host);
props.setProperty("mail.imaps.user", username);
props.setProperty("mail.imaps.password", password);
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("imaps");
// Connect to the specified server.
store.connect();
// Open the INBOX folder.
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
// Search for messages sent on a specific date.
Calendar cal = Calendar.getInstance();
cal.set(2021, Calendar.MAY, 1); // Set the date to May 1, 2021
Date searchDate = cal.getTime();
SearchTerm term = new ReceivedDateTerm(ComparisonTerm.EQ, searchDate);
Message[] messages = inbox.search(term);
// Find the most recent email with a specific subject.
Message latestMessage = null;
for (int i = messages.length - 1; i >= 0; i--) {
Message message = messages[i];
if (message.getSubject().equals("Your Subject Here")) {
latestMessage = message;
break;
}
}
// Print the content of the latest message.
if (latestMessage != null) {
System.out.println("Subject: " + latestMessage.getSubject());
System.out.println("From: " + Arrays.toString(latestMessage.getFrom()));
System.out.println("To: " + Arrays.toString(latestMessage.getRecipients(Message.RecipientType.TO)));
System.out.println("Date: " + latestMessage.getSentDate());
System.out.println("Content: " + latestMessage.getContent().toString());
} else {
System.out.println("No email found with the specified subject.");
}
// Close the folder and store objects.
inbox.close(false);
store.close();
}
}
```
请将 `your-hostname`, `your-username` 和 `your-password` 替换为您的实际值。此代码将连接到 IMAP 服务器,打开收件箱文件夹,搜索在指定日期发送的邮件,然后查找特定主题的最新邮件,并打印其内容。