Search code examples
javagmailjakarta-mailimap

How to properly delete a copied gmail message using javamail?


I have a scenario like this. I have copied a gmail message from Inbox to a child folder of Inbox, say test-folder. Now the message is there in Inbox and as well as in Inbox/test-folder. Now later if I want to delete (expunge) the copy in Inbox/test-folder using javamail, it is also being deleted from Inbox also.

I know that gmail maintains only 1 copy of the message in its database and it just tags folder names to the message, so it is obvious if I expunge it from other folder, it will also get deleted from the original folder.

The following code works for other IMAP based mails like yahoo and etc.

Folder inbox = store.getFolder("INBOX");
Folder child = store.getFolder("INBOX/test-folder");

inbox.open(Folder.READ_WRITE);
child.open(Folder.READ_WRITE);

AppendUID[] appendUIDs = inbox.copyUIDMessages(new Message[]{ message }, child);
AppendUID appendUID = appendUIDs[0];
long uid = appendUID.uid;

// EDIT: I have to close and reopen the child folder, otherwise getMessageByUID will return null.
child.close(false);
child.open(Folder.READ_WRITE);

Message copiedMessage = child.getMessageByUID(uid);

if (!copiedMessage.isExpunged() && !copiedMessage.isSet(Flags.Flag.DELETED)) {
    copiedMessage.setFlag(Flags.Flag.DELETED, true);
}

inbox.close(true);
child.close(true);

The above code delete only the message in Inbox/test-folder, not from Inbox for Yahoo and all. But for gmail it deletes the message from Inbox as well as Inbox/test-folder.

Email client like evolution, handles this scenario properly for gmail. It deletes the message only from the target folder. So how to achieve this using javamail or gimap library?

NOTE: I am using 1.5.5 of the javamail library.


Solution

  • Seems like that should work, but Gmail doesn't exactly follow the imap spec. What does the debug output show?