I have an IMAP Folder
opened as READ_ONLY
and I want to set a specific message as SEEN
(read) at a specific point in my program.
I tried to find a way to change the mode from READ_ONLY
to READ_WRITE
on the fly but apparently the only way to do this is closing the Folder
and opening it again.
I wrote a hefty method that achieves the above but I'm really unhappy about the situation.
If I open the folder as READ_WRITE
from the beginning, the messages gets marked as READ
during my processing, which is not the point of time that I want the message to be marked as READ
.
Here have a peek on the method that I wrote and don't giggle.
/**
* @param message The message to be processed.
* @param read True to mark as READ, False to mark as UNREAD.
*/
public static void markMessageAsRead(Message message, boolean read) {
try {
//Getting required variables
Folder messageFolder = message.getFolder();
int initialFolderMode = messageFolder.getMode();
boolean initialFolderOpenState = messageFolder.isOpen();
//If the folder is readonly then lets set it to readwrite
if(initialFolderMode == Folder.READ_ONLY) {
if(initialFolderOpenState) {
messageFolder.close(false);
}
messageFolder.open(Folder.READ_WRITE);
}
//Make sure folder is open (incase the above if didn't evaluate)
if(!initialFolderOpenState) {
messageFolder.open(Folder.READ_WRITE);
}
//Marking message as seen/unseen
message.setFlag(Flags.Flag.SEEN, read);
//Now lets revert the folder to it's state before it came here
if(initialFolderOpenState) {
if(!messageFolder.isOpen()) {
messageFolder.open(initialFolderMode);
}
} else {
if(messageFolder.isOpen()) {
messageFolder.close(false);
}
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
Is there a way to achieve what I want in a more neatly manner?
The conventional solution is to open the folder in read-write mode and then use the peek functionality when you want to fetch data without setting the seen
flag. Commands that peek do not set the seen
flag.