I am trying to create a folder if it does not exist and then copy a message from another folder to the destination folder. I am finding some strange behaviour that I can not understand. Given the following excerpt:
// messages is an array of Message instances.
// Source is the source folder
// destination is a string of the destination folder.
Folder dest = null;
try {
dest = store.getFolder(destination);
if (!dest.exists()) {
dest.create(Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS);
// Since folder's are not meant to cache I thought I'd get it again
// though this does not work either.
//dest.close(false);
//dest = store.getFolder(destination);
}
dest.open(Folder.READ_WRITE);
// Fails here
source.copyMessages(messages, dest);
source.setFlags(messages, new Flags(Flags.Flag.DELETED), true);
} catch (MessagingException ex) {
throw new MailProcessorException(ex.getMessage(), ex);
} finally {
if (dest != null) {
try {
dest.close(false);
} catch (MessagingException ex) {
System.err.println("Couldn't close destination folder.");
}
}
}
The following behaviour is examined:
- If the folder does not exist:
- The folder gets created
- An exception is thrown at
source.copyMessages.
- If the folder does exist:
- The messages are copied as expected.
- Messages are marked for deletion.
I am using JavaMail 1.4.6, also tried with 1.6.5.
This is really strange. Looking at your code and reading the docs, there should be no way that this is happening…
Could it be some problem with the mail server? Some databases use consistency models (see http://en.wikipedia.org/wiki/Eventual_consistency for example) that don’t always act the way you’d naively expect. Is there a chance you can try your code on a different mail server? Or, try to put a really long (30 seconds?)
Thread.sleep(...)before yourcopyMessages(...)call and see if that fixes it.If it does, what is happening is that your server creates the folder in one request, but this creation takes a while to reach the part of the server code that is handling the message copying. Then, unfortunately, I’m not sure if there is much you can do other than a retry if the copying fails or the artificial delay (which sucks).
Aside: The docs seem to say, that you can skip the
dest.open(Folder.READ_WRITE);if you like.