javamail mark gmail message as read

One liner that will do it WITHOUT downloading the entire message:

single message:

folder.setFlags(new Message[] {message}, new Flags(Flags.Flag.SEEN), true);

all messages:

folder.setFlags(messages, new Flags(Flags.Flag.SEEN), true);

Other methods of calling getContent() or creating a copy with new MimeMessage(original) cause the client to download the entire message, and creates a huge performance hit.

Note that the inbox must be opened for READ_WRITE:

folder.open(Folder.READ_WRITE);

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.


Well this post is old but the easiest solution hasn´t been posted yet.

You are accessing the Message. message.setFlag(Flag.SEEN, true);


for (Message message : messages) {
                    message.setFlag(Flags.Flag.SEEN,true);
                }

and change the below line

folder.open(Folder.READ_ONLY);

to this

folder.open(Folder.READ_WRITE);