How to mark messages that are received by an java application using javax Mail Api?
I want to create an application that gets all e-mails from an e-mail account using imap. When I first run the application I get all mails, than if I run it again I want to mark the messages that was read before so I can receive only new messages.
I found that Message Object contains Flags(System Flags and User defined flags), but I can't manage to set one user defined flag.
It is possible to mark the messages received by my application on the e-mail account, or I have to retain all message ids and every time when I get messages from imap I have to compare their 开发者_C百科id with retained ids and get only the messages that has different ids?
Some IMAP servers don't permit you to set user-defined flags. Most do, however. Via JavaMail, you'd do the following:
Flags flags = new Flags("fetched");
message.setFlags(flags, true);
Those flags aren't permanent, however -- another IMAP client could clear them just as easily as you set them. (Though they probably won't.)
Another option is to track the UIDs of the messages you've seen. You can get them via ImapFolder.getUID(Message)
. It's more straightforward than tracking Message-ID headers, which are much more costly to fetch and, since they're strings, occupy more memory in your app.
Yet another option is to use POP and track UIDL
s.
Yes it is possible to mark the messages as read, and when the next time you want to read the messages you can only read the new messages.
Use the following code:
Folder emailFolder = emailStore.getFolder("INBOX");
Message messages[] = emailFolder.search(new FlagTerm(new Flags(Flag.SEEN), false));
System.out.println("no of messages=" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
//here write your code to read the message and whatever you wanna do//
//now at the end of the message(remember at the end of the message u read using code) write the following code//
message.setFlag(Flag.SEEN, true);
}//end of for loop
精彩评论