Hi @Aleksandr ,
Thanks for reaching out.
I understand that you are using client credential flow to obtain the OAuth Token using v2.0 via IMAP and trying to read mail using JavaMail.
1.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:
2.Install ExchangeOnlineManagement Install-Module -Name ExchangeOnlineManagement -allowprerelease Import-module ExchangeOnlineManagement Connect-ExchangeOnline -Organization
3.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 "[******@contoso.com]" -User <SERVICE_PRINCIPAL_ID> -AccessRights FullAccess
4. In the application, you need to use scope = 'https://outlook.office365.com/.default '
Once you will 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.