Search code examples
javaemailimap

Imap folder shared mailbox - BAD Command received in Invalid state


Using JavaMail i have problems updating an imap folder of a shared mailbox or just listing all folders of the shared mailbox.
(Updating folder of main account is no problem)

Mail provider is: office365

final Properties props = new Properties();
props.put("mail.imap.starttls.enable", true);
props.put("mail.imap.auth", true);
props.put("mail.imap.ssl.trust", "*");
props.put("mail.imap.ssl.enable", true);
props.put("mail.imap.auth.plain.disable", true);
props.put("mail.imap.auth.ntlm.disable", true);
props.put("mail.imap.auth.gssapi.disable", true);

final Session mailSession = javax.mail.Session.getInstance(props);
mailSession.setDebug(true);

final Store store = mailSession.getStore("imap");

store.connect("outlook.office365.com", 993, "[email protected]/Info", "******");
// A1 LOGIN [email protected]/Info ******
// A1 OK LOGIN completed.
// A2 CAPABILITY
// * CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+
// A2 OK CAPABILITY completed.
// DEBUG IMAP: AUTH: PLAIN

A: Get List of folders

final Folder[] f = store.getDefaultFolder().list(); // list() throws exception
// A3 LIST "" "%"
// BAD Command received in Invalid state.

B: Update particular folder

final Folder folderSentItems = store.getFolder("Sent Items");
folderSentItems.open(Folder.READ_WRITE); // throws exception
// BAD Command received in Invalid state.
message.setFlag(Flag.SEEN, true);
folderSentItems.appendMessages(new Message[]
{
    message
});
store.close();

Wether I retrieve all folders a) or update any folder B, I get this exception:

Caused by: com.sun.mail.iap.BadCommandException: BAD Command received in Invalid state.

What is the problem?


Solution

  • After hours of searching and testing various user name combinations the following worked for me:

    The trick was not taking the alias shown in the outlook.office365.com admin panel but rather taking the user-name (may be the UserPrincipalName UPN) from admin panel portal.office.com. Also using a forward slash.

    The final login name in format: user/shared-mailbox-user-name

    Example:

    domain: example.com
    user: [email protected]
    password: abcdefg
    shared-mailbox: [email protected]
    shared-mailbox-user-name / UPN: [email protected]

    props.put("mail.imap.auth.plain.disable", true);
    props.put("mail.imap.auth.ntlm.disable", true);
    props.put("mail.imap.auth.gssapi.disable", true);
    
    store.connect("outlook.office365.com", 993, "[email protected]/[email protected]", "abcdefg");
    

    Update

    Office365 admin allows us now to update the user-name UPN so that we can use the shared mailbox itself. Then it would look like this

    store.connect("outlook.office365.com", 993, "[email protected]/[email protected]", "abcdefg");