Hi @javax.mail.AuthenticationFailedException , Thanks for updating the question in detail. As per the above code, you are using IMAP OAuth protocol with client credential flow to get the access token. You are not able to authenticate successfully as the service principal has not been registered successfully. For client credentials flow, you need to add application permissions under Office 365 Exchange Online
Make sure to grant admin consent for all the application permissions.
Once consent has been provided, the admin must register your AAD application's service principal in Exchange using powerShell by following commands:
Install ExchangeOnlineManagement
Install-Module -Name ExchangeOnlineManagement -allowprerelease Import-module ExchangeOnlineManagement Connect-ExchangeOnline -Organization
Register Service Principal in Exchange:
1.New-ServicePrincipal -AppId <APPLICATION_ID> -ServiceId <OBJECT_ID> [-Organization <ORGANIZATION_ID>]
Make sure to use ObjectId from enterprise applications rather than object id of application registration.
For the same application you registered in Application Registration. A corresponding application has been created in Enterprise Application as well. You need to pass object id from there while registering service principal in Exchange:
2.Get-ServicePrincipal | fl 3.Add-MailboxPermission -Identity "john.smith@contoso.com" -User <SERVICE_PRINCIPAL_ID> -AccessRights FullAccess In the application, you need to use scope = 'https://outlook.office365.com/.default ' Once you get the access token, you can create and open a Java Mail connection to read mails.
Properties props = new Properties();
props.put("mail.store.protocol", "imap");
props.put("mail.imap.host", "outlook.office365.com");
props.put("mail.imap.port", "993");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.auth", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
props.put("mail.imap.user", mailAddress);
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");
// open mailbox....
String token = getAuthToken(tanantId,clientId,client_secret);
Session session = Session.getInstance(props);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect("outlook.office365.com", mailAddress, token);
Hope this will help. Thanks, Shweta Please remember to "Accept Answer" if answer helped you.