Green Green - 6 months ago 114
Java Question

javamail mark gmail message as read

Note: added after answer:
Thanks.. Yeah I had tried the Flag.SEEN to true and saveChanges.. I also had read getContent marks it read. I tried using it in the for statement that loops through the messages. But I got the messages again from the folder anyways in the next loop. I was assuming the folder was live, so grabbing the content, then grabbing the messages again from the folder with the filter to not get any seen should work, but I was still getting the same message. I could try closing the folder and reopen as a test to see if it's marked. Also if I go over to my client and click the message, then my code stops seeing it even in the loop, so I was hoping to do the same in the code.

original:
I'm using javamail to get email from a gmail account, it's working great, when I get the message I'd like to mark it as read, can anyone give me some direction? Here is my current code:

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");

store.connect("imap.gmail.com", eUserName, ePassWord);
// Get folder
Folder folder = store.getFolder("INBOX");
if (folder == null || !folder.exists()) {
return null;
}
folder.open(Folder.READ_ONLY);

// Only pull unread
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[]; // = folder.search(ft);

for(int x = 0; x < timeOutInSeconds; x++) {
log.reportMessage("looking for emails");
try {
folder.getMessages();
messages = folder.search(ft);

if (messages.length > 0) {
for (Message message : messages) {
//log.reportMessage("found message: should not see again, marking read");
// want to mark as read

}
}
Thread.sleep(1000);
}
catch(Exception ex) {

}
}

// Close connection
folder.close(false);
store.close();
return null;

}
catch (NoSuchProviderException ex) {

return null;
}
catch (MessagingException ex) {

return null;
}


}

Answer

First of all, you can't mark a message as read if you are using a POP3 server - the POP3 protocol doesn't support that. However, the IMAP v4 protocol does.

You might think the way to do this is to get the message, set the Flags.Flag.SEEN flag to true, and then call message.saveChanges(). Oddly, this is not the case.

Instead, the JavaMail API Design Specification, Chapter 4, section "The Flags Class" states that the SEEN flag is implicitly set when the contents of a message are retrieved. So, to mark a message as read, you can use the following code:

myImapFolder.open(Folder.READ_WRITE);
myImapFolder.getMessage(myMsgID).getContent();
myImapFolder.close(false);

Or another way is to use the MimeMessage copy constructor, ie:

MimeMessage source = (MimeMessage) folder.getMessage(1)
MimeMessage copy = new MimeMessage(source);

When you construct the copy, the seen flag is implicitly set for the message referred to by source.