Connecting to outlook using javax.mail report "BAD User is authenticated but not connected"

Tao Ding 15 Reputation points
2023-01-31T06:05:08.2233333+00:00

Hi dear all!

I am using javax.mail connecting to outlook, the version of javax.mail is 1.6.2, maven config like :

        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>

and my java code like:

package com.example.demo.mail;

import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;


public class OutlookMail {

    private static final String IMAP_HOST = "outlook.office365.com";
    private static String ADDRESS = "xxx@outlook.com";

    private static String APP_PASSWORD = "xxx";
    private static Properties PROPERTIES = new Properties() {{
        setProperty("mail.imap.host", IMAP_HOST);
        setProperty("mail.imap.starttls.enable", "true");
    }};

    public static void main(String[] args) throws Exception {
        int i = 0;
        while (true) {
            i++;
            System.out.println("\n\n----------------------\nThe " + i + " time.");
            getInboxMessageCount();
        }
    }


    public static void getInboxMessageCount() throws Exception {
        Session session = Session.getInstance(PROPERTIES);
        session.setDebug(true);
        Store store = null;
        Folder folder = null;
        try {
            store = session.getStore("imap");
            store.connect(IMAP_HOST, ADDRESS, APP_PASSWORD);
            folder = store.getFolder("Inbox");
            folder.open(Folder.READ_ONLY);
            System.out.println("Inbox message count: " + folder.getMessageCount());
        } catch (Exception var) {
            throw new RuntimeException(var);
        } finally {
            if (null != folder) {
                folder.close();
            }
            if (null != store) {
                store.close();
            }
        }
    }

}

The APP_PASSWORD is not my outlook mail login password, it`s app password generate at outlook account security setting.

As you can see, my code is very simple, connect to outlook mail server through IMAP protocol and get INBOX folder message count.

The code is very unstable, it occasionally run failed and report 'BAD User is authenticated but not connected.'.

Here is log:

----------------------
The 76 time.
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: enable STARTTLS
DEBUG IMAP: closeFoldersOnStoreFailure
DEBUG IMAP: trying to connect to host "outlook.office365.com", port 143, isSSL false
* OK The Microsoft Exchange IMAP4 service is ready. [UwBHADIAUAAxADUAMwBDAEEAMAAwADAAMwAuAEEAUABDAFAAMQA1ADMALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
BX0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 LOGINDISABLED STARTTLS SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
BX0 OK CAPABILITY completed.
DEBUG IMAP: protocolConnect login, host=outlook.office365.com, user=singingfisher@outlook.com, password=<non-null>
BX1 STARTTLS
BX1 OK Begin TLS negotiation now.
BX2 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
BX2 OK CAPABILITY completed.
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAP: AUTHENTICATE PLAIN command result: BX3 OK AUTHENTICATE completed.
BX4 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CLIENTACCESSRULES CLIENTNETWORKPRESENCELOCATION BACKENDAUTHENTICATE CHILDREN IDLE NAMESPACE LITERAL+
BX4 OK CAPABILITY completed.
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: connection available -- size: 1
BX5 EXAMINE Inbox
* 40 EXISTS
* 40 RECENT
* FLAGS (\Seen \Answered \Flagged \Deleted \Draft $MDNSent)
* OK [PERMANENTFLAGS ()] Permanent flags
* OK [UNSEEN 16] Is the first unseen message
* OK [UIDVALIDITY 14] UIDVALIDITY value
* OK [UIDNEXT 211] The next unique identifier value
BX5 OK [READ-ONLY] EXAMINE completed.
Inbox message count: 40
BX6 CLOSE
BX6 OK CLOSE completed.
DEBUG IMAP: added an Authenticated connection -- size: 1
DEBUG IMAP: IMAPStore cleanup, force false
BX7 LOGOUT
* BYE Microsoft Exchange Server IMAP4 server signing off.
BX7 OK LOGOUT completed.
DEBUG IMAP: IMAPStore cleanup done


----------------------
The 77 time.
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: enable STARTTLS
DEBUG IMAP: closeFoldersOnStoreFailure
DEBUG IMAP: trying to connect to host "outlook.office365.com", port 143, isSSL false
* OK The Microsoft Exchange IMAP4 service is ready. [UwBHADIAUAAxADUAMwBDAEEAMAAwADEANwAuAEEAUABDAFAAMQA1ADMALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
BY0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 LOGINDISABLED STARTTLS SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
BY0 OK CAPABILITY completed.
DEBUG IMAP: protocolConnect login, host=outlook.office365.com, user=singingfisher@outlook.com, password=<non-null>
BY1 STARTTLS
BY1 OK Begin TLS negotiation now.
BY2 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
BY2 OK CAPABILITY completed.
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAP: AUTHENTICATE PLAIN command result: BY3 OK AUTHENTICATE completed.
BY4 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CLIENTACCESSRULES CLIENTNETWORKPRESENCELOCATION BACKENDAUTHENTICATE CHILDREN IDLE NAMESPACE LITERAL+
BY4 OK CAPABILITY completed.
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: connection available -- size: 1
BY5 EXAMINE Inbox
BY5 BAD User is authenticated but not connected.
BY6 LOGOUT
* BYE Microsoft Exchange Server IMAP4 server signing off.
BY6 OK LOGOUT completed.
Exception in thread "main" java.lang.IllegalStateException: This operation is not allowed on a closed folder
	at com.sun.mail.imap.IMAPFolder.close(IMAPFolder.java:1510)
	at com.sun.mail.imap.IMAPFolder.close(IMAPFolder.java:1484)
	at javax.mail.Folder.close(Folder.java:669)
	at com.example.demo.mail.OutlookMail.getInboxMessageCount(OutlookMail.java:49)
	at com.example.demo.mail.OutlookMail.main(OutlookMail.java:29)

As you can see, after 76 times succeed, the 77 time run failed. Is anyone faced the problem before? How can i fix this problem ?

Outlook
Outlook
A family of Microsoft email and calendar products.
2,959 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Vincent LE TOUX 0 Reputation points
    2023-11-21T14:27:20.5366667+00:00

    I got a similar problem in the past.
    It was related to the fact that the folder were not closed and that Exchange was stacking the connection.
    Apparently not the case here.

    0 comments No comments