Facing: AUTHENTICATE failed. Unable to authenticate through client credentials access token.

Vinay Sharma 51 Reputation points

I am trying to follow this document https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth. I was able to generate access_token through postman successfully.
But when I am using that access_token with javax.mail, I am facing AUTHENTICATE failed.
Below is the code and screenshot

    private void fetchMicrosoftMail() throws MessagingException {  
        Properties props = new Properties();  
        props.put("mail.imap.ssl.enable", "true");  
        props.setProperty("mail.imap.starttls.enable", "true");  
        props.put("mail.imap.auth.mechanisms", "XOAUTH2");  
        props.setProperty("mail.debug", "true");  
        Session session = Session.getInstance(props);  
        Store store = session.getStore("imap");  
        store.connect("outlook.office365.com", 993, "abc@example.com",  
        Folder[] folders = store.getDefaultFolder().list("*");  
        for (Folder folder : folders) {  

What I am doing wrong?

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
36,408 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. 2022-09-23T00:14:53.753+00:00

    Hello @Vinay Sharma , in order to succesfuly Authenticate an IMAP connection using OAuth client credentials with Azure AD you need to obtain an access token targeting the https://outlook.office.com/.default scope and encode the access token using the SASL XOAUTH2 format. E.g. base64("user=" + userName + "^Aauth=Bearer " + accessToken + "^A^A")

    In your code replace

       store.connect("outlook.office365.com", 993, "abc@example.com",  


       store.connect("outlook.office365.com", 993, "abc@example.com", "SASL XOAUTH2 encoded access token");  

    Let us know if you need additional assistance. If the answer was helpful, please accept it and complete the quality survey so that others can find a solution.