Connect to outlook Office 365 IMAP using OAUTH2

2020-04-28 07:25发布

问题:

Referred https://msdn.microsoft.com/en-us/office/office365/api/use-outlook-rest-api. Still I couldn't understand the AD, Outlook and windows live.

I got refresh token and access token from https://login.microsoftonline.com/common/oauth2/v2.0/authorize https://login.microsoftonline.com/common/oauth2/v2.0/token

and the scope

openid email profile offline_access https://outlook.office.com/mail.send https://outlook.office.com/mail.readwrite

Still i m getting error while connect imap using the access token.

imap.authenticate('XOAUTH2', 'xxxxxxx', access_token)
Net::IMAP::NoResponseError: AUTHENTICATE failed.

回答1:

For those asking about IMAP for personal accounts -- Outlook.com
-- re: comment

Apparently the scopes for the consumer Outlook.com (also live.com) is wl.imap.
See old Microsoft doc on Scopes and permissions.

Also have a look at this example where the same scope is mentioned:
http://afterlogic.com/mailbee-net/docs/OAuth2MicrosoftRegularAccountsInstalledApps.html

BTW, we came across the old Microsoft doc from Clever Components article:

https://www.clevercomponents.com/articles/article049/

  • note: their claim this is for Office365 may be questionable, perhaps a documentation error on their part

which has a link to a Microsoft doc:

https://msdn.microsoft.com/en-us/windows/desktop/dn440163

which has a link to Scopes and permissions in the related section listed at the end of the page:

https://msdn.microsoft.com/en-us/windows/desktop/hh243646

In the Clever Components article, they used two scopes wl.imap and wl.offline_access.
They noted that:

Microsoft recommends to use the "wl.offline_access" scope together with "wl.imap". Otherwise, an app can access the user's info only when a user signs in to Live Connect and uses your app."

So if your application needs continuous access then you need to include the offline access scope.



回答2:

I have finally gotten this to work. Interestingly I had to use the scope https://outlook.office365.com/IMAP.AccessAsUser.All although by now you have to register your app under the Graph API section in the Azure AD and the proposed Scope is https://graph.microsoft.com/IMAP.AccessAsUser.All which did not work for me (Authentication failed). Though I am not sure if that will change in the near future.

I used the properties as stated here: https://javaee.github.io/javamail/OAuth2

props.put("mail.imap.sasl.enable", "true");
props.put("mail.imap.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");