If your using Java Mail this this would be using IMAP for connectivity, the client credentials flow https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth which is what you would typically use for unattended access isn't currently supported (It will probably be supported at some point the future).
So you have a couple of options the first would be switch to using the Graph API https://github.com/microsoftgraph/msgraph-sdk-java which does support using the client credentials flow, its a bit more work but should offer generally a better and more secure solution going forward. The other solution would be look at using the ROPC oAuth flow https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc which essential means you have a set of credentials, obtain an Accesstoken for those credentials and apart form https://javaee.github.io/javamail/OAuth2 that should be all you need to do. Some of down sides of using the ROPC flow is you can't have MFA enabled on the account being used and you also can't have any conditional access polices.
For IMAP the only permission you need is https://outlook.office.com/IMAP.AccessAsUser.All (you'll find the permission themselves under the Graph API) and the registration needs to be done in the Azure Portal https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app to allow the ROPC flow you need to set the application registration to allow public flows