Xoauth2 ошибка подтверждения подлинности

Recently the support for OAuth 2.0 for IMAP and SMTP in the Exchange Online has been announced.
Following the guide I’ve set up the application permissions and IMAP and SMTP connection.
The application is configured as Accounts in any organizational directory (Any Azure AD directory - Multitenant) and uses authorization code flow.

URLs below are used for authorization:

  • https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize
  • https://login.microsoftonline.com/organizations/oauth2/v2.0/token

And the following Delegated Microsoft Graph scopes have been added:

enter image description here

The scopes, requests from code:

final List<String> scopes = Arrays.asList(
    "offline_access",
    "email",
    "openid",
    "profile",
    "User.Read",
    "Mail.ReadWrite",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

I successfully receive the access and refresh tokens:

{
    "token_type": "Bearer",
    "scope": "email IMAP.AccessAsUser.All Mail.ReadWrite openid profile SMTP.Send User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "edited",
    "refresh_token": "edited",
    "id_token": "edited"
}

Here’s the code, used to connect to IMAP:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

final Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, userEmail, accessToken);

Which generates the following output:

DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: enable SASL
DEBUG IMAPS: SASL mechanisms allowed: XOAUTH2
DEBUG IMAPS: closeFoldersOnStoreFailure
DEBUG IMAPS: trying to connect to host "outlook.office365.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADc...]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS:  XOAUTH2
DEBUG IMAPS: 
DEBUG IMAPS: SASL client XOAUTH2
DEBUG IMAPS: SASL callback length: 2
DEBUG IMAPS: SASL callback 0: javax.security.auth.callback.NameCallback@17046283
DEBUG IMAPS: SASL callback 1: javax.security.auth.callback.PasswordCallback@5bd03f44
A1 AUTHENTICATE XOAUTH2 dXNlcj1o...
A1 NO AUTHENTICATE failed.

Exception in thread "main" javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
    at javax.mail.Service.connect(Service.java:366)

And the following code is used for connecting to SMTP:

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
props.put("mail.smtp.auth.login.disable","true");
props.put("mail.smtp.auth.plain.disable","true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

Transport transport = session.getTransport("smtp");
transport.connect("smtp.office365.com", 587, userEmail, accessToken);

Which provides the output below:

DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 AM5PR0701CA0005.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 4 May 2020 15:52:28 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 SMTP server ready
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN XOAUTH2
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN XOAUTH2"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
AUTH XOAUTH2 dXNlcj1obW9kaUB...
535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]

Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]
    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
    at javax.mail.Service.connect(Service.java:366)

What I’ve also tried:

  • specifying scopes as https://graph.microsoft.com/SMTP.Send and just SMTP.Send
  • using https://login.microsoftonline.com/common/ url for authentication

Result is always the same.

Is it something I do wrong or there’s a bug somewhere in the support for this from the Microsoft side?

Update 1:

Tried from the command line, but same result:

$ openssl s_client -crlf -connect outlook.office365.com:993
... connection part omitted
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADYAUAAxADkAMgBDAEEAMAAwADkAMQAuAEUAVQBSAFAAMQA5ADIALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
C01 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
C01 OK CAPABILITY completed.
A01 AUTHENTICATE XOAUTH2 dXNlcj1obW9kaUBjb...
A01 NO AUTHENTICATE failed.
* BYE Connection is closed. 13
read:errno=0

Update 2:

Tried to create brand new application in the Azure Portal with the following permissions:

enter image description here

And receiving the following screen, when trying to give consent for scopes:

enter image description here

That is odd, because the permissions from Azure Portal don’t specify that the Admin consent is required and my previous app registration doesn’t show such screen when IMAP and SMTP scopes are requested.

Update 3:

Thanks to comments to this post I tried the following scopes:

public static final List<String> SCOPES = Arrays.asList(
    "offline_access",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Which gave me the token below:

{
    "token_type": "Bearer",
    "scope": "https://outlook.office365.com/IMAP.AccessAsUser.All https://outlook.office365.com/SMTP.Send",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1....",
    "refresh_token": "OAQABAAAAAAAm...."
}

IMAP/SMTP auth was successful and I was able to read the inbox + send an email!

But for my application I need also couple of other scopes to use some MS Graph API endpoints (read user profile, messages subscription and messages deletion).

So I tried different scopes:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access",
        "User.Read",
        "Mail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

This gave the token (note that scope value differs from the token that actually worked, the permissions don’t have outlook url):

{
    "token_type": "Bearer",
    "scope": "IMAP.AccessAsUser.All Mail.ReadWrite SMTP.Send User.Read profile openid email",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1Q...",
    "refresh_token": "OAQABAAAAAAAm..."
}

Which led to the result I got previously:

A1 NO AUTHENTICATE failed.

Trying all the scopes to be as URLs:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access", // or "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access"
        "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
        "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Leads to the following error when obtaining the token (the consent step passed successfully):

{
    "error": "invalid_request",
    "error_description": "AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope offline_access https://graph.microsoft.com/user.read https://graph.microsoft.com/mail.readwrite https://outlook.office365.com/imap.accessasuser.all https://outlook.office365.com/smtp.send is not valid.rnTrace ID: c3282396-6231-4e11-8300-77bc2ca57f00rnCorrelation ID: 5f5145bf-7114-4e6c-ab11-30e7ff84a056rnTimestamp: 2020-05-06 08:08:48Z",
    "error_codes": [
        28000
    ],
    "timestamp": "2020-05-06 08:08:48Z",
    "trace_id": "c3282396-6231-4e11-8300-77bc2ca57f00",
    "correlation_id": "5f5145bf-7114-4e6c-ab11-30e7ff84a056"
}

And when trying all the scopes to have microsoft graph (as copied from the Azure Portal)

public static final List<String> SCOPES = Arrays.asList(
    "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access",
    "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
    "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
    "https%3A%2F%2Fgraph.microsoft.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Fgraph.microsoft.com%2FSMTP.Send"
);

Return the following token (without a refresh token althout offline_access has been requested)

{
    "token_type": "Bearer",
    "scope": "profile openid email https://graph.microsoft.com/IMAP.AccessAsUser.All https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/SMTP.Send https://graph.microsoft.com/User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1..."
}

No success:

A1 NO AUTHENTICATE failed.

So it appears that if you don’t specify Outlook url for scope it’s assumed probably as Graph one which doesn’t allow authorization through IMAP and SMTP.

Update 4:

By requesting all the scopes I need at consent step, then getting first access token with only Graph scopes and the second one using refresh token endpoint specifying Outlook scopes — it worked.
Refresh token method for getting second access token is used because if you try to obtains access token by auth code you’ll get get the following error:

{
    "error": "invalid_grant",
    "error_description": "AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.rnTrace ID: 09fc80f4-f5fd-4e52-938f-d56b71dd0900rnCorrelation ID: 4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44rnTimestamp: 2020-05-08 12:13:30Z",
    "error_codes": [
        54005
    ],
    "timestamp": "2020-05-08 12:13:30Z",
    "trace_id": "09fc80f4-f5fd-4e52-938f-d56b71dd0900",
    "correlation_id": "4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44"
}

So no I’ll need to use two separate tokens depending on what resource I’ll need to manage.

Update 5:

If it still doesn’t work — check if your organization has Security Default enabled — they disable POP/IMAP/SMTP auth for accounts — https://techcommunity.microsoft.com/t5/exchange-team-blog/announcing-oauth-2-0-support-for-imap-and-smtp-auth-protocols-in/bc-p/1544725/highlight/true#M28589

Recently, I am trying to get e-mails from Gmail, using XOAuth2 protocol.
Especially, I am using «OAuth2Authenticator.java» from https://code.google.com/p/google-mail-oauth2-tools/downloads/list.

But, I always get an invalid credential error like the follwoing:

A1 NO [ALERT] Invalid credentials (Failure)
Exception in thread «main» javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:566)
at javax.mail.Service.connect(Service.java:265)

Before reading, due to the limitation of putting a link, I cannot write «httoo://» so that please think of that this http header is front of some url information.

Before posting this question, I think I looked most of the articles about this one. Many articles are about using OAuth1.0 (deprecated) But, I still cannot figure out how I can make it work with OAuth2 & XOAuth2. I appreciate any suggestion/helps.

The following is the steps I am taking:

  1. get an access token through OAuth2 with the scope of mail.google.com/

  2. just put this access token & gmail account (e.g. test@gmail.com) into «OAuth2Authenticator.java».

After this procedure, I always get invalid credential.

The interesting stuff is that I can get unread mails through Feed URL (i.e. https://mail.google.com/mail/feed/atom) which is specified in Google OAuth2.0 Playground.

This indicates that I am sure that I get the correct access token. But, does not work at all for IMAP with this sample code.

Actually, the scope «mail.google.com/» is not included in the list of Google OAuth2.0 Playground.

For getting access token for XOAuth2, is there any other special way to get access token?

For the official page about XOAuth2, we need to use base64 to encode the access token.
But, I think the sample code is doing this procedure.

Also, SMTP of this sample did not work at all. But, after changing the properties, I could make it work. Is this code old?
But, unfortunately, what I need is IMAP. But, after trying setting some different/new properties, IMAP does not work at all….

I am stuck on this problem for a long time. So, I posted this question.
I really appreciate any suggestion/helps.

Regards

Recently, I am trying to get e-mails from Gmail, using XOAuth2 protocol.
Especially, I am using «OAuth2Authenticator.java» from https://code.google.com/p/google-mail-oauth2-tools/downloads/list.

But, I always get an invalid credential error like the follwoing:

A1 NO [ALERT] Invalid credentials (Failure)
Exception in thread «main» javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:566)
at javax.mail.Service.connect(Service.java:265)

Before reading, due to the limitation of putting a link, I cannot write «httoo://» so that please think of that this http header is front of some url information.

Before posting this question, I think I looked most of the articles about this one. Many articles are about using OAuth1.0 (deprecated) But, I still cannot figure out how I can make it work with OAuth2 & XOAuth2. I appreciate any suggestion/helps.

The following is the steps I am taking:

  1. get an access token through OAuth2 with the scope of mail.google.com/

  2. just put this access token & gmail account (e.g. test@gmail.com) into «OAuth2Authenticator.java».

After this procedure, I always get invalid credential.

The interesting stuff is that I can get unread mails through Feed URL (i.e. https://mail.google.com/mail/feed/atom) which is specified in Google OAuth2.0 Playground.

This indicates that I am sure that I get the correct access token. But, does not work at all for IMAP with this sample code.

Actually, the scope «mail.google.com/» is not included in the list of Google OAuth2.0 Playground.

For getting access token for XOAuth2, is there any other special way to get access token?

For the official page about XOAuth2, we need to use base64 to encode the access token.
But, I think the sample code is doing this procedure.

Also, SMTP of this sample did not work at all. But, after changing the properties, I could make it work. Is this code old?
But, unfortunately, what I need is IMAP. But, after trying setting some different/new properties, IMAP does not work at all….

I am stuck on this problem for a long time. So, I posted this question.
I really appreciate any suggestion/helps.

Regards

Recently the support for OAuth 2.0 for IMAP and SMTP in the Exchange Online has been announced.
Following the guide I’ve set up the application permissions and IMAP and SMTP connection.
The application is configured as Accounts in any organizational directory (Any Azure AD directory - Multitenant) and uses authorization code flow.

URLs below are used for authorization:

  • https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize
  • https://login.microsoftonline.com/organizations/oauth2/v2.0/token

And the following Delegated Microsoft Graph scopes have been added:

enter image description here

The scopes, requests from code:

final List<String> scopes = Arrays.asList(
    "offline_access",
    "email",
    "openid",
    "profile",
    "User.Read",
    "Mail.ReadWrite",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

I successfully receive the access and refresh tokens:

{
    "token_type": "Bearer",
    "scope": "email IMAP.AccessAsUser.All Mail.ReadWrite openid profile SMTP.Send User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "edited",
    "refresh_token": "edited",
    "id_token": "edited"
}

Here’s the code, used to connect to IMAP:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

final Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, userEmail, accessToken);

Which generates the following output:

DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: enable SASL
DEBUG IMAPS: SASL mechanisms allowed: XOAUTH2
DEBUG IMAPS: closeFoldersOnStoreFailure
DEBUG IMAPS: trying to connect to host "outlook.office365.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADc...]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS:  XOAUTH2
DEBUG IMAPS: 
DEBUG IMAPS: SASL client XOAUTH2
DEBUG IMAPS: SASL callback length: 2
DEBUG IMAPS: SASL callback 0: javax.security.auth.callback.NameCallback@17046283
DEBUG IMAPS: SASL callback 1: javax.security.auth.callback.PasswordCallback@5bd03f44
A1 AUTHENTICATE XOAUTH2 dXNlcj1o...
A1 NO AUTHENTICATE failed.

Exception in thread "main" javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
    at javax.mail.Service.connect(Service.java:366)

And the following code is used for connecting to SMTP:

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
props.put("mail.smtp.auth.login.disable","true");
props.put("mail.smtp.auth.plain.disable","true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

Transport transport = session.getTransport("smtp");
transport.connect("smtp.office365.com", 587, userEmail, accessToken);

Which provides the output below:

DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 AM5PR0701CA0005.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 4 May 2020 15:52:28 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 SMTP server ready
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN XOAUTH2
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN XOAUTH2"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
AUTH XOAUTH2 dXNlcj1obW9kaUB...
535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]

Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]
    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
    at javax.mail.Service.connect(Service.java:366)

What I’ve also tried:

  • specifying scopes as https://graph.microsoft.com/SMTP.Send and just SMTP.Send
  • using https://login.microsoftonline.com/common/ url for authentication

Result is always the same.

Is it something I do wrong or there’s a bug somewhere in the support for this from the Microsoft side?

Update 1:

Tried from the command line, but same result:

$ openssl s_client -crlf -connect outlook.office365.com:993
... connection part omitted
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADYAUAAxADkAMgBDAEEAMAAwADkAMQAuAEUAVQBSAFAAMQA5ADIALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
C01 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
C01 OK CAPABILITY completed.
A01 AUTHENTICATE XOAUTH2 dXNlcj1obW9kaUBjb...
A01 NO AUTHENTICATE failed.
* BYE Connection is closed. 13
read:errno=0

Update 2:

Tried to create brand new application in the Azure Portal with the following permissions:

enter image description here

And receiving the following screen, when trying to give consent for scopes:

enter image description here

That is odd, because the permissions from Azure Portal don’t specify that the Admin consent is required and my previous app registration doesn’t show such screen when IMAP and SMTP scopes are requested.

Update 3:

Thanks to comments to this post I tried the following scopes:

public static final List<String> SCOPES = Arrays.asList(
    "offline_access",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Which gave me the token below:

{
    "token_type": "Bearer",
    "scope": "https://outlook.office365.com/IMAP.AccessAsUser.All https://outlook.office365.com/SMTP.Send",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1....",
    "refresh_token": "OAQABAAAAAAAm...."
}

IMAP/SMTP auth was successful and I was able to read the inbox + send an email!

But for my application I need also couple of other scopes to use some MS Graph API endpoints (read user profile, messages subscription and messages deletion).

So I tried different scopes:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access",
        "User.Read",
        "Mail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

This gave the token (note that scope value differs from the token that actually worked, the permissions don’t have outlook url):

{
    "token_type": "Bearer",
    "scope": "IMAP.AccessAsUser.All Mail.ReadWrite SMTP.Send User.Read profile openid email",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1Q...",
    "refresh_token": "OAQABAAAAAAAm..."
}

Which led to the result I got previously:

A1 NO AUTHENTICATE failed.

Trying all the scopes to be as URLs:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access", // or "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access"
        "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
        "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Leads to the following error when obtaining the token (the consent step passed successfully):

{
    "error": "invalid_request",
    "error_description": "AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope offline_access https://graph.microsoft.com/user.read https://graph.microsoft.com/mail.readwrite https://outlook.office365.com/imap.accessasuser.all https://outlook.office365.com/smtp.send is not valid.rnTrace ID: c3282396-6231-4e11-8300-77bc2ca57f00rnCorrelation ID: 5f5145bf-7114-4e6c-ab11-30e7ff84a056rnTimestamp: 2020-05-06 08:08:48Z",
    "error_codes": [
        28000
    ],
    "timestamp": "2020-05-06 08:08:48Z",
    "trace_id": "c3282396-6231-4e11-8300-77bc2ca57f00",
    "correlation_id": "5f5145bf-7114-4e6c-ab11-30e7ff84a056"
}

And when trying all the scopes to have microsoft graph (as copied from the Azure Portal)

public static final List<String> SCOPES = Arrays.asList(
    "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access",
    "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
    "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
    "https%3A%2F%2Fgraph.microsoft.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Fgraph.microsoft.com%2FSMTP.Send"
);

Return the following token (without a refresh token althout offline_access has been requested)

{
    "token_type": "Bearer",
    "scope": "profile openid email https://graph.microsoft.com/IMAP.AccessAsUser.All https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/SMTP.Send https://graph.microsoft.com/User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1..."
}

No success:

A1 NO AUTHENTICATE failed.

So it appears that if you don’t specify Outlook url for scope it’s assumed probably as Graph one which doesn’t allow authorization through IMAP and SMTP.

Update 4:

By requesting all the scopes I need at consent step, then getting first access token with only Graph scopes and the second one using refresh token endpoint specifying Outlook scopes — it worked.
Refresh token method for getting second access token is used because if you try to obtains access token by auth code you’ll get get the following error:

{
    "error": "invalid_grant",
    "error_description": "AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.rnTrace ID: 09fc80f4-f5fd-4e52-938f-d56b71dd0900rnCorrelation ID: 4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44rnTimestamp: 2020-05-08 12:13:30Z",
    "error_codes": [
        54005
    ],
    "timestamp": "2020-05-08 12:13:30Z",
    "trace_id": "09fc80f4-f5fd-4e52-938f-d56b71dd0900",
    "correlation_id": "4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44"
}

So no I’ll need to use two separate tokens depending on what resource I’ll need to manage.

Update 5:

If it still doesn’t work — check if your organization has Security Default enabled — they disable POP/IMAP/SMTP auth for accounts — https://techcommunity.microsoft.com/t5/exchange-team-blog/announcing-oauth-2-0-support-for-imap-and-smtp-auth-protocols-in/bc-p/1544725/highlight/true#M28589

Outlook 2016 Outlook for Microsoft 365 Outlook 2019 Еще…Меньше

Проблемы

При использовании IMAP для подключения к учетной записи электронной почты в Microsoft Outlook 2016, проверка подлинности завершается неудачно.

Причина

Такое поведение наблюдается, поскольку символ Юникода имеет пароль, подобное одному из следующих:

äöü

Обходной путь

Для решения проблемы используйте один из указанных ниже способов.

Метод 1: Изменение пароля

Измените пароль, поэтому он больше не содержит знаки Юникода.

Способ 2: Используйте другой протокол, чем IMAP

Можно настроить учетную запись электронной почты для использования протокола POP3 вместо IMAP, если сервер электронной почты поддерживает подключения POP3. Ниже будет создан новый профиль Outlook, будет настроено для соединения с использованием POP3. Примечание. Протокол POP3 загрузки электронной почты на локальном компьютере и он удаляется с сервера, тогда как IMAP оставляет копию сообщения электронной почты на сервере. Дополнительные сведения содержатся в разделе Понимание различий между POP3 и IMAP4.

  1. Закройте приложение Outlook.

  2. На панели управления щелкните или дважды щелкните значок Почта. Чтобы найти элемент электронной почты, откройте панель управления и введите в поле поиска в верхней части окна сообщений. Элемент управления панель для Windows XP введите в поле адрес электронной почты .

  3. Нажмите кнопку Показать.

  4. Нажмите кнопку Добавить.

  5. Введите имя профиля и нажмите кнопку ОК.

  6. Выберите ручной установкиили дополнительные типы серверови нажмите кнопку Далее.

  7. Выберите POP или IMAPи нажмите кнопку Далее.

  8. Введите ваши имя и адрес электронной почты и выберите Тип учетной записиPOP3 .

  9. Введите сервер входящей почты и сведения о SMTP-сервер исходящей почты, учетные данные для входа и нажмите кнопку Далее. Примечание. Посетите веб-узел узла сервера электронной почты или свяжитесь с ними для сбора сведений сервера входящей и исходящей почты.

  10. Чтобы убедиться в их правильности будет выполнена проверка настройки учетной записи:

    • Если тесты выполнены успешно, нажмите кнопку Закрыть.

    • Если появляется сообщение об ошибке во время тестов нажмите кнопку Закрыть. Исправить сведения в настройки учетной записи, а затем повторите шаги 9 и 10 о правильности настроек учетной записи.

  11. Нажмите кнопку Завершить.

  12. Почтаубедитесь, что выбран параметр всегда использовать этот профиль и выберите новое имя профиля из списка.

  13. Нажмите кнопку ОК.

Способ 3: Использовать Outlook 2013

Если возможно используйте Outlook 2013 вместо Outlook 2016 для подключения к учетной записи IMAP. Эта проблема не возникает в Outlook 2013.

Статус

Корпорация Майкрософт работает над устранением этой проблемы и опубликует дополнительную информацию в этой статье, когда информация станет доступной.

Нужна дополнительная помощь?

Нужны дополнительные параметры?

Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.

В сообществах можно задавать вопросы и отвечать на них, отправлять отзывы и консультироваться с экспертами разных профилей.

Recently the support for OAuth 2.0 for IMAP and SMTP in the Exchange Online has been announced.
Following the guide I’ve set up the application permissions and IMAP and SMTP connection.
The application is configured as Accounts in any organizational directory (Any Azure AD directory - Multitenant) and uses authorization code flow.

URLs below are used for authorization:

  • https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize
  • https://login.microsoftonline.com/organizations/oauth2/v2.0/token

And the following Delegated Microsoft Graph scopes have been added:

enter image description here

The scopes, requests from code:

final List<String> scopes = Arrays.asList(
    "offline_access",
    "email",
    "openid",
    "profile",
    "User.Read",
    "Mail.ReadWrite",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

I successfully receive the access and refresh tokens:

{
    "token_type": "Bearer",
    "scope": "email IMAP.AccessAsUser.All Mail.ReadWrite openid profile SMTP.Send User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "edited",
    "refresh_token": "edited",
    "id_token": "edited"
}

Here’s the code, used to connect to IMAP:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

final Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, userEmail, accessToken);

Which generates the following output:

DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: enable SASL
DEBUG IMAPS: SASL mechanisms allowed: XOAUTH2
DEBUG IMAPS: closeFoldersOnStoreFailure
DEBUG IMAPS: trying to connect to host "outlook.office365.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADc...]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS:  XOAUTH2
DEBUG IMAPS: 
DEBUG IMAPS: SASL client XOAUTH2
DEBUG IMAPS: SASL callback length: 2
DEBUG IMAPS: SASL callback 0: javax.security.auth.callback.NameCallback@17046283
DEBUG IMAPS: SASL callback 1: javax.security.auth.callback.PasswordCallback@5bd03f44
A1 AUTHENTICATE XOAUTH2 dXNlcj1o...
A1 NO AUTHENTICATE failed.

Exception in thread "main" javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
    at javax.mail.Service.connect(Service.java:366)

And the following code is used for connecting to SMTP:

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
props.put("mail.smtp.auth.login.disable","true");
props.put("mail.smtp.auth.plain.disable","true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

Transport transport = session.getTransport("smtp");
transport.connect("smtp.office365.com", 587, userEmail, accessToken);

Which provides the output below:

DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 AM5PR0701CA0005.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 4 May 2020 15:52:28 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 SMTP server ready
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN XOAUTH2
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN XOAUTH2"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
AUTH XOAUTH2 dXNlcj1obW9kaUB...
535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]

Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]
    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
    at javax.mail.Service.connect(Service.java:366)

What I’ve also tried:

  • specifying scopes as https://graph.microsoft.com/SMTP.Send and just SMTP.Send
  • using https://login.microsoftonline.com/common/ url for authentication

Result is always the same.

Is it something I do wrong or there’s a bug somewhere in the support for this from the Microsoft side?

Update 1:

Tried from the command line, but same result:

$ openssl s_client -crlf -connect outlook.office365.com:993
... connection part omitted
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADYAUAAxADkAMgBDAEEAMAAwADkAMQAuAEUAVQBSAFAAMQA5ADIALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
C01 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
C01 OK CAPABILITY completed.
A01 AUTHENTICATE XOAUTH2 dXNlcj1obW9kaUBjb...
A01 NO AUTHENTICATE failed.
* BYE Connection is closed. 13
read:errno=0

Update 2:

Tried to create brand new application in the Azure Portal with the following permissions:

enter image description here

And receiving the following screen, when trying to give consent for scopes:

enter image description here

That is odd, because the permissions from Azure Portal don’t specify that the Admin consent is required and my previous app registration doesn’t show such screen when IMAP and SMTP scopes are requested.

Update 3:

Thanks to comments to this post I tried the following scopes:

public static final List<String> SCOPES = Arrays.asList(
    "offline_access",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Which gave me the token below:

{
    "token_type": "Bearer",
    "scope": "https://outlook.office365.com/IMAP.AccessAsUser.All https://outlook.office365.com/SMTP.Send",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1....",
    "refresh_token": "OAQABAAAAAAAm...."
}

IMAP/SMTP auth was successful and I was able to read the inbox + send an email!

But for my application I need also couple of other scopes to use some MS Graph API endpoints (read user profile, messages subscription and messages deletion).

So I tried different scopes:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access",
        "User.Read",
        "Mail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

This gave the token (note that scope value differs from the token that actually worked, the permissions don’t have outlook url):

{
    "token_type": "Bearer",
    "scope": "IMAP.AccessAsUser.All Mail.ReadWrite SMTP.Send User.Read profile openid email",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1Q...",
    "refresh_token": "OAQABAAAAAAAm..."
}

Which led to the result I got previously:

A1 NO AUTHENTICATE failed.

Trying all the scopes to be as URLs:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access", // or "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access"
        "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
        "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Leads to the following error when obtaining the token (the consent step passed successfully):

{
    "error": "invalid_request",
    "error_description": "AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope offline_access https://graph.microsoft.com/user.read https://graph.microsoft.com/mail.readwrite https://outlook.office365.com/imap.accessasuser.all https://outlook.office365.com/smtp.send is not valid.rnTrace ID: c3282396-6231-4e11-8300-77bc2ca57f00rnCorrelation ID: 5f5145bf-7114-4e6c-ab11-30e7ff84a056rnTimestamp: 2020-05-06 08:08:48Z",
    "error_codes": [
        28000
    ],
    "timestamp": "2020-05-06 08:08:48Z",
    "trace_id": "c3282396-6231-4e11-8300-77bc2ca57f00",
    "correlation_id": "5f5145bf-7114-4e6c-ab11-30e7ff84a056"
}

And when trying all the scopes to have microsoft graph (as copied from the Azure Portal)

public static final List<String> SCOPES = Arrays.asList(
    "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access",
    "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
    "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
    "https%3A%2F%2Fgraph.microsoft.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Fgraph.microsoft.com%2FSMTP.Send"
);

Return the following token (without a refresh token althout offline_access has been requested)

{
    "token_type": "Bearer",
    "scope": "profile openid email https://graph.microsoft.com/IMAP.AccessAsUser.All https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/SMTP.Send https://graph.microsoft.com/User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1..."
}

No success:

A1 NO AUTHENTICATE failed.

So it appears that if you don’t specify Outlook url for scope it’s assumed probably as Graph one which doesn’t allow authorization through IMAP and SMTP.

Update 4:

By requesting all the scopes I need at consent step, then getting first access token with only Graph scopes and the second one using refresh token endpoint specifying Outlook scopes — it worked.
Refresh token method for getting second access token is used because if you try to obtains access token by auth code you’ll get get the following error:

{
    "error": "invalid_grant",
    "error_description": "AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.rnTrace ID: 09fc80f4-f5fd-4e52-938f-d56b71dd0900rnCorrelation ID: 4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44rnTimestamp: 2020-05-08 12:13:30Z",
    "error_codes": [
        54005
    ],
    "timestamp": "2020-05-08 12:13:30Z",
    "trace_id": "09fc80f4-f5fd-4e52-938f-d56b71dd0900",
    "correlation_id": "4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44"
}

So no I’ll need to use two separate tokens depending on what resource I’ll need to manage.

Update 5:

If it still doesn’t work — check if your organization has Security Default enabled — they disable POP/IMAP/SMTP auth for accounts — https://techcommunity.microsoft.com/t5/exchange-team-blog/announcing-oauth-2-0-support-for-imap-and-smtp-auth-protocols-in/bc-p/1544725/highlight/true#M28589

Recently, I am trying to get e-mails from Gmail, using XOAuth2 protocol.
Especially, I am using «OAuth2Authenticator.java» from https://code.google.com/p/google-mail-oauth2-tools/downloads/list.

But, I always get an invalid credential error like the follwoing:

A1 NO [ALERT] Invalid credentials (Failure)
Exception in thread «main» javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:566)
at javax.mail.Service.connect(Service.java:265)

Before reading, due to the limitation of putting a link, I cannot write «httoo://» so that please think of that this http header is front of some url information.

Before posting this question, I think I looked most of the articles about this one. Many articles are about using OAuth1.0 (deprecated) But, I still cannot figure out how I can make it work with OAuth2 & XOAuth2. I appreciate any suggestion/helps.

The following is the steps I am taking:

  1. get an access token through OAuth2 with the scope of mail.google.com/

  2. just put this access token & gmail account (e.g. test@gmail.com) into «OAuth2Authenticator.java».

After this procedure, I always get invalid credential.

The interesting stuff is that I can get unread mails through Feed URL (i.e. https://mail.google.com/mail/feed/atom) which is specified in Google OAuth2.0 Playground.

This indicates that I am sure that I get the correct access token. But, does not work at all for IMAP with this sample code.

Actually, the scope «mail.google.com/» is not included in the list of Google OAuth2.0 Playground.

For getting access token for XOAuth2, is there any other special way to get access token?

For the official page about XOAuth2, we need to use base64 to encode the access token.
But, I think the sample code is doing this procedure.

Also, SMTP of this sample did not work at all. But, after changing the properties, I could make it work. Is this code old?
But, unfortunately, what I need is IMAP. But, after trying setting some different/new properties, IMAP does not work at all….

I am stuck on this problem for a long time. So, I posted this question.
I really appreciate any suggestion/helps.

Regards

Recently, I am trying to get e-mails from Gmail, using XOAuth2 protocol.
Especially, I am using «OAuth2Authenticator.java» from https://code.google.com/p/google-mail-oauth2-tools/downloads/list.

But, I always get an invalid credential error like the follwoing:

A1 NO [ALERT] Invalid credentials (Failure)
Exception in thread «main» javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:566)
at javax.mail.Service.connect(Service.java:265)

Before reading, due to the limitation of putting a link, I cannot write «httoo://» so that please think of that this http header is front of some url information.

Before posting this question, I think I looked most of the articles about this one. Many articles are about using OAuth1.0 (deprecated) But, I still cannot figure out how I can make it work with OAuth2 & XOAuth2. I appreciate any suggestion/helps.

The following is the steps I am taking:

  1. get an access token through OAuth2 with the scope of mail.google.com/

  2. just put this access token & gmail account (e.g. test@gmail.com) into «OAuth2Authenticator.java».

After this procedure, I always get invalid credential.

The interesting stuff is that I can get unread mails through Feed URL (i.e. https://mail.google.com/mail/feed/atom) which is specified in Google OAuth2.0 Playground.

This indicates that I am sure that I get the correct access token. But, does not work at all for IMAP with this sample code.

Actually, the scope «mail.google.com/» is not included in the list of Google OAuth2.0 Playground.

For getting access token for XOAuth2, is there any other special way to get access token?

For the official page about XOAuth2, we need to use base64 to encode the access token.
But, I think the sample code is doing this procedure.

Also, SMTP of this sample did not work at all. But, after changing the properties, I could make it work. Is this code old?
But, unfortunately, what I need is IMAP. But, after trying setting some different/new properties, IMAP does not work at all….

I am stuck on this problem for a long time. So, I posted this question.
I really appreciate any suggestion/helps.

Regards

Recently the support for OAuth 2.0 for IMAP and SMTP in the Exchange Online has been announced.
Following the guide I’ve set up the application permissions and IMAP and SMTP connection.
The application is configured as Accounts in any organizational directory (Any Azure AD directory - Multitenant) and uses authorization code flow.

URLs below are used for authorization:

  • https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize
  • https://login.microsoftonline.com/organizations/oauth2/v2.0/token

And the following Delegated Microsoft Graph scopes have been added:

enter image description here

The scopes, requests from code:

final List<String> scopes = Arrays.asList(
    "offline_access",
    "email",
    "openid",
    "profile",
    "User.Read",
    "Mail.ReadWrite",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

I successfully receive the access and refresh tokens:

{
    "token_type": "Bearer",
    "scope": "email IMAP.AccessAsUser.All Mail.ReadWrite openid profile SMTP.Send User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "edited",
    "refresh_token": "edited",
    "id_token": "edited"
}

Here’s the code, used to connect to IMAP:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

final Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, userEmail, accessToken);

Which generates the following output:

DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: enable SASL
DEBUG IMAPS: SASL mechanisms allowed: XOAUTH2
DEBUG IMAPS: closeFoldersOnStoreFailure
DEBUG IMAPS: trying to connect to host "outlook.office365.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADc...]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS:  XOAUTH2
DEBUG IMAPS: 
DEBUG IMAPS: SASL client XOAUTH2
DEBUG IMAPS: SASL callback length: 2
DEBUG IMAPS: SASL callback 0: javax.security.auth.callback.NameCallback@17046283
DEBUG IMAPS: SASL callback 1: javax.security.auth.callback.PasswordCallback@5bd03f44
A1 AUTHENTICATE XOAUTH2 dXNlcj1o...
A1 NO AUTHENTICATE failed.

Exception in thread "main" javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
    at javax.mail.Service.connect(Service.java:366)

And the following code is used for connecting to SMTP:

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
props.put("mail.smtp.auth.login.disable","true");
props.put("mail.smtp.auth.plain.disable","true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

Transport transport = session.getTransport("smtp");
transport.connect("smtp.office365.com", 587, userEmail, accessToken);

Which provides the output below:

DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 AM5PR0701CA0005.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 4 May 2020 15:52:28 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 SMTP server ready
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN XOAUTH2
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN XOAUTH2"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
AUTH XOAUTH2 dXNlcj1obW9kaUB...
535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]

Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]
    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
    at javax.mail.Service.connect(Service.java:366)

What I’ve also tried:

  • specifying scopes as https://graph.microsoft.com/SMTP.Send and just SMTP.Send
  • using https://login.microsoftonline.com/common/ url for authentication

Result is always the same.

Is it something I do wrong or there’s a bug somewhere in the support for this from the Microsoft side?

Update 1:

Tried from the command line, but same result:

$ openssl s_client -crlf -connect outlook.office365.com:993
... connection part omitted
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADYAUAAxADkAMgBDAEEAMAAwADkAMQAuAEUAVQBSAFAAMQA5ADIALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
C01 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
C01 OK CAPABILITY completed.
A01 AUTHENTICATE XOAUTH2 dXNlcj1obW9kaUBjb...
A01 NO AUTHENTICATE failed.
* BYE Connection is closed. 13
read:errno=0

Update 2:

Tried to create brand new application in the Azure Portal with the following permissions:

enter image description here

And receiving the following screen, when trying to give consent for scopes:

enter image description here

That is odd, because the permissions from Azure Portal don’t specify that the Admin consent is required and my previous app registration doesn’t show such screen when IMAP and SMTP scopes are requested.

Update 3:

Thanks to comments to this post I tried the following scopes:

public static final List<String> SCOPES = Arrays.asList(
    "offline_access",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Which gave me the token below:

{
    "token_type": "Bearer",
    "scope": "https://outlook.office365.com/IMAP.AccessAsUser.All https://outlook.office365.com/SMTP.Send",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1....",
    "refresh_token": "OAQABAAAAAAAm...."
}

IMAP/SMTP auth was successful and I was able to read the inbox + send an email!

But for my application I need also couple of other scopes to use some MS Graph API endpoints (read user profile, messages subscription and messages deletion).

So I tried different scopes:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access",
        "User.Read",
        "Mail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

This gave the token (note that scope value differs from the token that actually worked, the permissions don’t have outlook url):

{
    "token_type": "Bearer",
    "scope": "IMAP.AccessAsUser.All Mail.ReadWrite SMTP.Send User.Read profile openid email",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1Q...",
    "refresh_token": "OAQABAAAAAAAm..."
}

Which led to the result I got previously:

A1 NO AUTHENTICATE failed.

Trying all the scopes to be as URLs:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access", // or "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access"
        "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
        "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Leads to the following error when obtaining the token (the consent step passed successfully):

{
    "error": "invalid_request",
    "error_description": "AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope offline_access https://graph.microsoft.com/user.read https://graph.microsoft.com/mail.readwrite https://outlook.office365.com/imap.accessasuser.all https://outlook.office365.com/smtp.send is not valid.rnTrace ID: c3282396-6231-4e11-8300-77bc2ca57f00rnCorrelation ID: 5f5145bf-7114-4e6c-ab11-30e7ff84a056rnTimestamp: 2020-05-06 08:08:48Z",
    "error_codes": [
        28000
    ],
    "timestamp": "2020-05-06 08:08:48Z",
    "trace_id": "c3282396-6231-4e11-8300-77bc2ca57f00",
    "correlation_id": "5f5145bf-7114-4e6c-ab11-30e7ff84a056"
}

And when trying all the scopes to have microsoft graph (as copied from the Azure Portal)

public static final List<String> SCOPES = Arrays.asList(
    "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access",
    "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
    "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
    "https%3A%2F%2Fgraph.microsoft.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Fgraph.microsoft.com%2FSMTP.Send"
);

Return the following token (without a refresh token althout offline_access has been requested)

{
    "token_type": "Bearer",
    "scope": "profile openid email https://graph.microsoft.com/IMAP.AccessAsUser.All https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/SMTP.Send https://graph.microsoft.com/User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1..."
}

No success:

A1 NO AUTHENTICATE failed.

So it appears that if you don’t specify Outlook url for scope it’s assumed probably as Graph one which doesn’t allow authorization through IMAP and SMTP.

Update 4:

By requesting all the scopes I need at consent step, then getting first access token with only Graph scopes and the second one using refresh token endpoint specifying Outlook scopes — it worked.
Refresh token method for getting second access token is used because if you try to obtains access token by auth code you’ll get get the following error:

{
    "error": "invalid_grant",
    "error_description": "AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.rnTrace ID: 09fc80f4-f5fd-4e52-938f-d56b71dd0900rnCorrelation ID: 4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44rnTimestamp: 2020-05-08 12:13:30Z",
    "error_codes": [
        54005
    ],
    "timestamp": "2020-05-08 12:13:30Z",
    "trace_id": "09fc80f4-f5fd-4e52-938f-d56b71dd0900",
    "correlation_id": "4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44"
}

So no I’ll need to use two separate tokens depending on what resource I’ll need to manage.

Update 5:

If it still doesn’t work — check if your organization has Security Default enabled — they disable POP/IMAP/SMTP auth for accounts — https://techcommunity.microsoft.com/t5/exchange-team-blog/announcing-oauth-2-0-support-for-imap-and-smtp-auth-protocols-in/bc-p/1544725/highlight/true#M28589

Outlook 2016 Outlook for Microsoft 365 Outlook 2019 Еще…Меньше

Проблемы

При использовании IMAP для подключения к учетной записи электронной почты в Microsoft Outlook 2016, проверка подлинности завершается неудачно.

Причина

Такое поведение наблюдается, поскольку символ Юникода имеет пароль, подобное одному из следующих:

äöü

Обходной путь

Для решения проблемы используйте один из указанных ниже способов.

Метод 1: Изменение пароля

Измените пароль, поэтому он больше не содержит знаки Юникода.

Способ 2: Используйте другой протокол, чем IMAP

Можно настроить учетную запись электронной почты для использования протокола POP3 вместо IMAP, если сервер электронной почты поддерживает подключения POP3. Ниже будет создан новый профиль Outlook, будет настроено для соединения с использованием POP3. Примечание. Протокол POP3 загрузки электронной почты на локальном компьютере и он удаляется с сервера, тогда как IMAP оставляет копию сообщения электронной почты на сервере. Дополнительные сведения содержатся в разделе Понимание различий между POP3 и IMAP4.

  1. Закройте приложение Outlook.

  2. На панели управления щелкните или дважды щелкните значок Почта. Чтобы найти элемент электронной почты, откройте панель управления и введите в поле поиска в верхней части окна сообщений. Элемент управления панель для Windows XP введите в поле адрес электронной почты .

  3. Нажмите кнопку Показать.

  4. Нажмите кнопку Добавить.

  5. Введите имя профиля и нажмите кнопку ОК.

  6. Выберите ручной установкиили дополнительные типы серверови нажмите кнопку Далее.

  7. Выберите POP или IMAPи нажмите кнопку Далее.

  8. Введите ваши имя и адрес электронной почты и выберите Тип учетной записиPOP3 .

  9. Введите сервер входящей почты и сведения о SMTP-сервер исходящей почты, учетные данные для входа и нажмите кнопку Далее. Примечание. Посетите веб-узел узла сервера электронной почты или свяжитесь с ними для сбора сведений сервера входящей и исходящей почты.

  10. Чтобы убедиться в их правильности будет выполнена проверка настройки учетной записи:

    • Если тесты выполнены успешно, нажмите кнопку Закрыть.

    • Если появляется сообщение об ошибке во время тестов нажмите кнопку Закрыть. Исправить сведения в настройки учетной записи, а затем повторите шаги 9 и 10 о правильности настроек учетной записи.

  11. Нажмите кнопку Завершить.

  12. Почтаубедитесь, что выбран параметр всегда использовать этот профиль и выберите новое имя профиля из списка.

  13. Нажмите кнопку ОК.

Способ 3: Использовать Outlook 2013

Если возможно используйте Outlook 2013 вместо Outlook 2016 для подключения к учетной записи IMAP. Эта проблема не возникает в Outlook 2013.

Статус

Корпорация Майкрософт работает над устранением этой проблемы и опубликует дополнительную информацию в этой статье, когда информация станет доступной.

Нужна дополнительная помощь?

Недавно было объявлено о поддержке OAuth 2.0 для IMAP и SMTP в Exchange Online. Следуя руководству, я настроил разрешения приложений и IMAP и SMTP-соединение. Приложение настроено какAccounts in any organizational directory (Any Azure AD directory - Multitenant)и использует поток кода авторизации.

Нижеуказанные URL-адреса используются для авторизации:

  • https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize
  • https://login.microsoftonline.com/organizations/oauth2/v2.0/token

Были добавлены следующие делегированные области Microsoft Graph:

Объемы, запросы из кода:

final List<String> scopes = Arrays.asList(
    "offline_access",
    "email",
    "openid",
    "profile",
    "User.Read",
    "Mail.ReadWrite",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Я успешно получаю токены доступа и обновления:

{
    "token_type": "Bearer",
    "scope": "email IMAP.AccessAsUser.All Mail.ReadWrite openid profile SMTP.Send User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "edited",
    "refresh_token": "edited",
    "id_token": "edited"
}

Вот код, используемый для подключения к IMAP:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "[email protected]";
String accessToken = "access_token_received_on_previous_step";

final Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, userEmail, accessToken);

Что дает следующий результат:

DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: enable SASL
DEBUG IMAPS: SASL mechanisms allowed: XOAUTH2
DEBUG IMAPS: closeFoldersOnStoreFailure
DEBUG IMAPS: trying to connect to host "outlook.office365.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADc...]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, [email protected], password=<non-null>
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS:  XOAUTH2
DEBUG IMAPS: 
DEBUG IMAPS: SASL client XOAUTH2
DEBUG IMAPS: SASL callback length: 2
DEBUG IMAPS: SASL callback 0: [email protected]
DEBUG IMAPS: SASL callback 1: [email protected]
A1 AUTHENTICATE XOAUTH2 dXNlcj1o...
A1 NO AUTHENTICATE failed.

Exception in thread "main" javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
    at javax.mail.Service.connect(Service.java:366)

А для подключения к SMTP используется следующий код:

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
props.put("mail.smtp.auth.login.disable","true");
props.put("mail.smtp.auth.plain.disable","true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "[email protected]";
String accessToken = "access_token_received_on_previous_step";

Transport transport = session.getTransport("smtp");
transport.connect("smtp.office365.com", 587, userEmail, accessToken);

Что дает результат ниже:

DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 AM5PR0701CA0005.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 4 May 2020 15:52:28 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 SMTP server ready
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN XOAUTH2
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN XOAUTH2"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.office365.com, [email protected], password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
AUTH XOAUTH2 dXNlcj1obW9kaUB...
535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]

Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]
    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
    at javax.mail.Service.connect(Service.java:366)

Что еще пробовал:

  • определение областей как https://graph.microsoft.com/SMTP.Send и просто SMTP.Send
  • с помощью https://login.microsoftonline.com/common/ URL для аутентификации

Результат всегда один и тот же.

Я что-то делаю неправильно или где-то есть ошибка в поддержке со стороны Microsoft?

Обновление 1:

Пробовал из командной строки, но результат тот же:

$ openssl s_client -crlf -connect outlook.office365.com:993
... connection part omitted
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADYAUAAxADkAMgBDAEEAMAAwADkAMQAuAEUAVQBSAFAAMQA5ADIALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
C01 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
C01 OK CAPABILITY completed.
A01 AUTHENTICATE XOAUTH2 dXNlcj1obW9kaUBjb...
A01 NO AUTHENTICATE failed.
* BYE Connection is closed. 13
read:errno=0

Обновление 2:

Пытался создать новое приложение на портале Azure со следующими разрешениями:

И получение следующего экрана при попытке дать согласие на области:

Это странно, потому что в разрешениях портала Azure не указано, что требуется согласие администратора, а моя предыдущая регистрация приложения не показывает такой экран, когда запрашиваются области IMAP и SMTP.

Обновление 3:

Благодаря комментариям к этой публикации я попробовал следующие области:

public static final List<String> SCOPES = Arrays.asList(
    "offline_access",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Что дало мне токен ниже:

{
    "token_type": "Bearer",
    "scope": "https://outlook.office365.com/IMAP.AccessAsUser.All https://outlook.office365.com/SMTP.Send",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1....",
    "refresh_token": "OAQABAAAAAAAm...."
}

IMAP / SMTP аутентификация прошла успешно, и я смог прочитать входящие + отправить электронное письмо!

Но для моего приложения мне также нужна пара других областей для использования некоторых конечных точек API MS Graph (чтение профиля пользователя, подписка на сообщения и удаление сообщений).

Поэтому я пробовал разные прицелы:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access",
        "User.Read",
        "Mail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Это дало токен (обратите внимание, что значение области отличается от токена, который фактически работал, разрешения не имеют URL-адреса Outlook):

{
    "token_type": "Bearer",
    "scope": "IMAP.AccessAsUser.All Mail.ReadWrite SMTP.Send User.Read profile openid email",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1Q...",
    "refresh_token": "OAQABAAAAAAAm..."
}

Что привело к результату, который я получил ранее:

A1 NO AUTHENTICATE failed.

Попытка сделать все области как URL-адреса:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access", // or "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access"
        "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
        "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

Приводит к следующей ошибке при получении токена (этап согласия прошел успешно):

{
    "error": "invalid_request",
    "error_description": "AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope offline_access https://graph.microsoft.com/user.read https://graph.microsoft.com/mail.readwrite https://outlook.office365.com/imap.accessasuser.all https://outlook.office365.com/smtp.send is not valid.rnTrace ID: c3282396-6231-4e11-8300-77bc2ca57f00rnCorrelation ID: 5f5145bf-7114-4e6c-ab11-30e7ff84a056rnTimestamp: 2020-05-06 08:08:48Z",
    "error_codes": [
        28000
    ],
    "timestamp": "2020-05-06 08:08:48Z",
    "trace_id": "c3282396-6231-4e11-8300-77bc2ca57f00",
    "correlation_id": "5f5145bf-7114-4e6c-ab11-30e7ff84a056"
}

И при попытке всех областей иметь график microsoft (скопированный с портала Azure)

public static final List<String> SCOPES = Arrays.asList(
    "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access",
    "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
    "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
    "https%3A%2F%2Fgraph.microsoft.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Fgraph.microsoft.com%2FSMTP.Send"
);

Верните следующий токен (без токена обновления, хотя был запрошен offline_access)

{
    "token_type": "Bearer",
    "scope": "profile openid email https://graph.microsoft.com/IMAP.AccessAsUser.All https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/SMTP.Send https://graph.microsoft.com/User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1..."
}

Безуспешно:

A1 NO AUTHENTICATE failed.

Таким образом, похоже, что если вы не укажете URL-адрес Outlook для области, он, вероятно, будет принят как Graph, который не разрешает авторизацию через IMAP и SMTP.

Обновление 4:

Запрашивая все области, которые мне нужны на этапе согласия, затем получал первый токен доступа только с областями Graph, а второй — с использованием конечной точки токена обновления, определяющей области Outlook, — это сработало. Метод обновления токена используется для получения второго токена доступа, потому что если вы попытаетесь получить токен доступа с помощью кода аутентификации, вы получите следующую ошибку:

{
    "error": "invalid_grant",
    "error_description": "AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.rnTrace ID: 09fc80f4-f5fd-4e52-938f-d56b71dd0900rnCorrelation ID: 4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44rnTimestamp: 2020-05-08 12:13:30Z",
    "error_codes": [
        54005
    ],
    "timestamp": "2020-05-08 12:13:30Z",
    "trace_id": "09fc80f4-f5fd-4e52-938f-d56b71dd0900",
    "correlation_id": "4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44"
}

Так что нет, мне нужно будет использовать два отдельных токена в зависимости от того, каким ресурсом мне нужно управлять.

Обновление 5:

Если это все еще не работает — проверьте, включена ли в вашей организации безопасность по умолчанию — они отключают аутентификацию POP/IMAP/SMTP для учетных записей — https://techcommunity.microsoft.com/t5/exchange-team-blog/announcing-oauth-2-0-support-for-imap-and-smtp-auth-protocols-in/bc-p/1544725/highlight/true

  • Remove From My Forums
  • Вопрос

  • Добрый день, уважаемые коллеги.
    При подключении постового ящика через IMAP к Exchange 2007 клиент Outlook 2007 выходит ошибка

    Вход на сервер входящей почты (IMAP) Сбой проверки подлинности. Общие. На данном компьютере не поддерживается ни один из способов проверки подлинности, поддерживаемых сервером IMAP (если таковы имеются)

    на сервере у ящика IMAP Enabled.  Как решить данную проблему не подскажете?

    • Перемещено

      12 марта 2012 г. 8:41
      forum merge (От:Exchange Server 2007)

Ответы

  • Вы это прочитать можете?)

    Я вижу у вас включено SSL. Вы клиента соответствующим образом настраиваете? Отключите в настройках IMAP SSL, переключите на plain text и проверьте на клиенте. Скорее всего у вас на клиенте не включено SSL для IMAP.

    Для правильного функционирования SSL вам надо сгенерировать сертификат с правильным именем, импортировать его в exchange и включить для службы IMAP.

    • Предложено в качестве ответа
      Nikita PanovModerator
      10 декабря 2009 г. 7:48
    • Помечено в качестве ответа
      Nikita PanovModerator
      21 декабря 2009 г. 10:09

Я пытаюсь подключить почтовый ящик Outlook с помощью imap.

Область, определенная для приложения: Разрешение API

Я генерирую токен, используя поток учетных данных клиента:

Ниже приведен запрос, который я отправляю, чтобы получить токен доступа.

grant_type=client_credentials&client_id=MyClientID&client_secret=Mysecret&scope=https://outlook.office.com/.default

Я успешно получил токен.

Вот код, используемый для подключения к IMAP из Java:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
String accessToken = "access_token_received_on_previous_step";
final Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "user@outlook.com", accessToken);

Получение ниже ошибки:

A1 AUTHENTICATE XOAUTH2 dXNlcj1zb29yeW.........
A1 NO AUTHENTICATE failed.
javax.mail.AuthenticationFailedException: AUTHENTICATE failed.

Может ли кто-нибудь помочь мне решить проблему

1 ответ

Вы назначили Microsoft Graph делегированное разрешение IMAP.AccessAsUser.All в приложении Azure AD. Но делегированное разрешение не поддерживается для типа предоставления client_credentials.

На основе документация:

Доступ OAuth к протоколам IMAP, POP, SMTP AUTH через поток предоставления учетных данных клиента OAuth2 не поддерживается.

И вам нужно использовать OAuth2 поток кода авторизации или Процесс предоставления авторизации устройства OAuth2.

Кроме того, я думаю, вам может понадобиться установить scope как https://graph.microsoft.com/.default, потому что разрешение теперь находится в Microsoft Graph.


1

Allen Wu
22 Июл 2020 в 03:59

После регистрации пользователя при попытке отослать письмо для подтверждения регистрации с помощью smtp google на сайте выдает ошибку:

Failed to authenticate on SMTP server with username "mysite@gmail.com" using 3 possible authenticators. Authenticator LOGIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials r12sm7919415ljh.105 - gsmtp ". Authenticator PLAIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials r12sm7919415ljh.105 - gsmtp ". Authenticator XOAUTH2 returned Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials r12sm7919415ljh.105 - gsmtp

в .env вроде все указано верно

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mysite@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

DEVIL

  • #2

Код:

++ Starting Swift_SmtpTransport
<< 220 iva8-b81aeb0c8234.qloud-c.yandex.net ESMTP (Want to use Yandex.Mail for your domain? Visit http://pdd.yandex.ru)

>> EHLO forum.ru

<< 250-iva8-b81aeb0c8234.qloud-c.yandex.net
250-8BITMIME
250-PIPELINING
250-SIZE 42991616
250-AUTH LOGIN PLAIN XOAUTH2
250-DSN
250 ENHANCEDSTATUSCODES

>> AUTH LOGIN

<< 334 VXNlcm5hbWU6

>> c3VwcG9ydEB2aWNlLXNhbXAucnU=

<< 334 UGFzc3dvcmQ6

>> Nzc1OTk4MjgyODA=

<< 535 5.7.8 Error: authentication failed: Invalid user or password!

!! Expected response code 235 but got code "535", with message "535 5.7.8 Error: authentication failed: Invalid user or password!
" (code: 535)
>> RSET

<< 250 2.0.0 Ok

>> AUTH PLAIN c3VwcG9ydEB2aWNlLXNhbXAucnUAc3VwcG9ydEB2aWNlLXNhbXAucnUANzc1OTk4MjgyODA=

<< 535 5.7.8 Error: authentication failed: Invalid user or password!

!! Expected response code 235 but got code "535", with message "535 5.7.8 Error: authentication failed: Invalid user or password!
" (code: 535)
>> RSET

<< 250 2.0.0 Ok

>> AUTH XOAUTH2 dXNlcj1zdXBwb3J0QHZpY2Utc2FtcC5ydQFhdXRoPUJlYXJlciA3NzU5OTgyODI4MAEB

<< 535 5.7.8 Error: authentication failed: Invalid user or password!

!! Expected response code 235 but got code "535", with message "535 5.7.8 Error: authentication failed: Invalid user or password!
" (code: 535)
>> RSET

<< 250 2.0.0 Ok

При проверке исходящей почты вылазит такая ошибка. Поиском пользовался, но так и не нашел решения проблемы. Возможно, что с паролем накосячил. Но как тогда его узнать, пароль от доменной почты?

Тут же написано
Error: authentication failed: Invalid user or password!

В смысле как узнать?

Timofey228

  • #3

Тут же написано
Error: authentication failed: Invalid user or password!

В смысле как узнать?

Так я его указал, все равно эта ошибка

Экстрим

  • #4

Так я его указал, все равно эта ошибка

ну так же все указано: ошибка при аутентификации, неверный логин или пароль

Timofey228

  • #5

ну так же все указано: ошибка при аутентификации, неверный логин или пароль

вот поэтому и написал, потому что не знаю, что не так сделал

Экстрим

  • #6

вот поэтому и написал, потому что не знаю, что не так сделал

указали неверный логин либо пароль. Как подробнее объяснить?)

DreamTails

Timofey228

  • #8

указали неверный логин либо пароль. Как подробнее объяснить?)

Я указал доменную почту support@site.ru и пароль от основного ящика.

  • #10

Точно верно всё настроили и используете судя по ошибке.
Want to use Yandex.Mail for your domain? Visit http://pdd.yandex.ru

Timofey228

  • #11

У Вас недостаточно прав для просмотра ссылок.
Вход или Регистрация

Идеальный мануал

Заходим в раздел админки НастройкиНастройки электронной почты. В поле адрес для возврата писем указываем созданный вами почтовый ящик. Ставим галочку автоматической обработки недоставленных писем и указываем данные для захода на ваш служебный почтовый ящик, которые вы создали ранее: адрес (в случае собственного SMTP-сервера — свой и указывайте), логин (адрес, который вы создали) и пароль от ящика.

Я по этой инструкции и настраивал как раз

Точно верно всё настроили и используете судя по ошибке.
Want to use Yandex.Mail for your domain? Visit http://pdd.yandex.ru

Да, использую smpt сервис от Яндекса

Последнее редактирование модератором: 29 Янв 2021

  • #12

То есть, после создания почтового ящика, Вы зашли в него и всё там подтвердили?

Timofey228

  • #13

То есть, после создания почтового ящика, Вы зашли в него и всё там подтвердили?

Верно, следовал строго инструкции

  • #14

Я бы порекомендовал всё проверить, плюс показать настройки, но всё в теме мануала, если по нему настраивали.

Timofey228

  • #15

Проблема решена.
Можете закрывать.
Спасибо всем за помощь, особенно Mirovinger :)

Экстрим

  • #16

Проблема решена.
Можете закрывать.
Спасибо всем за помощь, особенно Mirovinger :)

так а что не так было? Чтобы другие знали, если возникнет проблема

Timofey228

  • #17

так а что не так было? Чтобы другие знали, если возникнет проблема

Были некорректные настройки. Я все сбросил и начал настраивать с нуля, следуя инструкции. И все получилось.

Я использую следующий код для отправки электронной почты. Код работает правильно на моем локальном компьютере. Но на рабочем сервере, я получаю сообщение об ошибке

        var fromAddress = new MailAddress("mymailid@gmail.com");
        var fromPassword = "xxxxxx";
        var toAddress = new MailAddress("yourmailid@yourdoamain.com");

        string subject = "subject";
        string body = "body";

        System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword)

        };

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })


        smtp.Send(message);

и на моем Gmail A / c я получил следующее письмо после того, как я запустил код с производственного сервера

Привет ,

кто-то недавно использовал ваш пароль, чтобы попытаться войти в Google
Счет mymailid@gmail.com — … Этот человек использовал приложение, такое
как электронная почта, клиент или мобильное устройство.

мы предотвратили попытку входа в систему, если это был угонщик, пытающийся
доступ к учетной записи. Пожалуйста, ознакомьтесь с деталями попытки входа в систему:

пятница, 3 январь 2014 13:56: 08 часов UTC IP-адрес: xxx.xx.xx.xxx
(abcd.net.) Местонахождение: Philadelphia PA, Philadelphia, PA, USA

Если вы не распознаете эту попытку входа, кто-то другой может быть
пытается получить доступ к вашей учетной записи. Вы должны войти в свой счет и
немедленно сбросьте пароль.

сброс пароля

Если это вы и у вас возникли проблемы с доступом к вашей учетной записи,
выполните действия по устранению неполадок в
http://support.google.com/mail?p=client_login

Искренне Ваш, команда учетных записей Google

21 ответов


обычно это происходит при попытке входа в систему из другого часового пояса или IP-адреса компьютера. Рабочий сервер и используемый почтовый идентификатор находятся в разных часовых поясах. Выберите любое из одного решения:

1) Войдите на рабочий сервер через удаленный доступ и войдите в gmail один раз с вашими учетными данными. Они запросят подтверждение, подтвердят его и выйдут из системы.

или 2) Войдите в gmail на свой локальный компьютер, следуйте этому ссылке и выбрать обзор этой деятельности и принять надлежащие меры.


при попытке отправить почту с кодом и найти ошибку «SMTP-сервер требует защищенного соединения или клиент не прошел проверку подлинности. Ответ сервера был: 5.5.1 требуется аутентификация», чем ошибка может возникнуть из-за следующих случаев.

Пример 1: когда пароль неправильный

Пример 2: при попытке войти в систему из некоторого приложения

случай 3: при попытке входа домен, отличный от вашего часового пояса / домена / компьютера
(это имеет место в большинстве сценариев при отправке почты из кода)

существует решение для каждого

решение для случая 1: введите правильный пароль.

Решение 1 для случая 2: перейдите в настройки безопасности по следующей ссылке https://www.google.com/settings/security/lesssecureapps и включить меньше безопасные приложения . Так что вы сможете войти в систему из всех приложений.

решение 2 для случая 2: (см.https://stackoverflow.com/a/9572958/52277) включите двухфакторную аутентификацию (он же двухэтапная проверка) , а затем создайте пароль для конкретного приложения. Используйте этот новый пароль для аутентификации через SMTP.

Решение 1 для случая 3: (Это может быть полезно) вам нужно просмотреть действие. но, анализируя деятельность не будет полезна из-за последних стандартов безопасности ссылка не будет полезна. Поэтому попробуйте следующий случай.

решение 2 для случая 3: Если вы разместили свой код где-то на производственном сервере и если у вас есть доступ к производственному серверу, то возьмите подключение удаленного рабочего стола к производственному серверу и попробуйте войти один раз из браузера производственного сервера.
Это добавит excpetioon для входа в google, и вам будет разрешено войти из код.

но что, если у вас нет доступа к рабочему серверу.
попробуйте решение 3

решение 3 для случая 3: вы должны включить вход из другого часового пояса / ip для вашей учетной записи google.

для этого перейдите по ссылке https://g.co/allowaccess и разрешить доступ, нажав кнопку Продолжить.

и это все. Вот, держи. Теперь ты сможете войти с любого компьютера и с помощью любого приложения в свой аккаунт google.


Это проблема безопасности, Gmail по умолчанию предотвращает доступ для вашей учетной записи электронной почты из пользовательских приложений. Вы можете настроить его, чтобы принять логин из вашего приложения.

после входа на ваш e-mail,НАЖМИТЕ ЗДЕСЬ

Это приведет вас к следующей странице

Less Secure Apps Page


проведя пару часов сегодня, пробуя каждое решение здесь, я все еще не смог пройти мимо этой точной ошибки. Я использовал gmail много раз таким образом, поэтому я знал, что это было что-то глупое, но ничего я не сделал, исправил проблему. Я, наконец, наткнулся на решение в моем случае, поэтому думал, что поделюсь.

во-первых, большинство ответов выше также требуются, но в моем случае это был простой вопрос упорядочения кода при создании SmtpClient класс.

в этом первом фрагменте кода ниже обратите внимание, где находится строка» Credentials = creds». Эта реализация создаст ошибку, указанную в этом вопросе, даже если все остальное настроено правильно.

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient
        {
            Host = Emailer.Host,
            Port = Emailer.Port,
            Credentials = creds,
            EnableSsl = Emailer.RequireSSL,
            UseDefaultCredentials = false,
            DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network
        }

однако, если вы переместите вызов установщика учетных данных вниз, электронное письмо будет отправлено без ошибок. Я не внес никаких изменений в окружающий код … то есть … имя пользователя / пароль и т. д. Очевидно, либо EnableSSL, UseDefaultCredentials, или DeliveryMethod зависит от учетных данных, устанавливаемых в первую очередь….Я не проверял все, чтобы выяснить, какой это был.

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient
        {
            Host = Emailer.Host,
            Port = Emailer.Port,
            EnableSsl = Emailer.RequireSSL,
            UseDefaultCredentials = false,
            DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
            Credentials = creds
        }

надеюсь, это поможет спасти кого-то от головной боли в будущем.


Привет у меня была такая же проблема,

что я сделал, чтобы решить. это включить менее безопасное приложение.
после подключения к моей учетной записи gmail. Я ввел эту ссылку:https://www.google.com/settings/security/lesssecureapps

затем я включаю безопасное приложение и, и это сработало.
это было сказано также выше

10

автор: Barak Rosenfeld


просто выполните шаг в электронной почте google и включите менее безопасные приложения.


Я столкнулся с той же проблемой. Это происходит, когда вы включаете проверку 2 шага (MFA).
Просто выключите 2 шага проверки и ваша проблема должна быть решена.


Ниже приведен мой код.У меня также была та же ошибка, но проблема заключалась в том, что я дал свой пароль неправильно.Приведенный ниже код будет работать отлично..попробуйте!—2—>

            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");             
            mail.From = new MailAddress("fromaddress@gmail.com");
            mail.To.Add("toaddress1@gmail.com");
            mail.To.Add("toaddress2@gmail.com");
            mail.Subject = "Password Recovery ";
            mail.Body += " <html>";
            mail.Body += "<body>";
            mail.Body += "<table>";
            mail.Body += "<tr>";
            mail.Body += "<td>User Name : </td><td> HAi </td>";
            mail.Body += "</tr>";

            mail.Body += "<tr>";
            mail.Body += "<td>Password : </td><td>aaaaaaaaaa</td>";
            mail.Body += "</tr>";
            mail.Body += "</table>";
            mail.Body += "</body>";
            mail.Body += "</html>";
            mail.IsBodyHtml = true;
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("sendfrommailaddress.com", "password");
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);

вы можете сослаться на него в мой блог


у меня была такая же проблема для приложения, развернутого в Microsoft Azure.

SmtpException: SMTP-серверу требуется безопасное соединение или
клиент не прошел проверку подлинности. Ответ сервера: 5.5.1
Требуется Аутентификация.

сначала я одобрил все неизвестные устройства (некоторые ip-адреса, происходящие из Ирландии) на следующей странице (подписан как gmail пользователь):
https://security.google.com/settings/u/1/security/secureaccount

я использовал следующие настройки для клиента:

var client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("my_user_name@gmail.com", "my_password"); 

он начал работать только после того, как я установил следующее свойство на smtp-клиенте:

client.TargetName = "STARTTLS/smtp.gmail.com";

то, что сработало для меня, было активировать опцию для менее безопасных приложений (я использую VB.NET)

Public Shared Sub enviaDB(ByRef body As String, ByRef file_location As String)
        Dim mail As New MailMessage()
        Dim SmtpServer As New SmtpClient("smtp.gmail.com")
        mail.From = New MailAddress("from@gmail.com")
        mail.[To].Add("to@gmail.com")
        mail.Subject = "subject"
        mail.Body = body
        Dim attachment As System.Net.Mail.Attachment
        attachment = New System.Net.Mail.Attachment(file_location)
        mail.Attachments.Add(attachment)
        SmtpServer.Port = 587
        SmtpServer.Credentials = New System.Net.NetworkCredential("user", "password")
        SmtpServer.EnableSsl = True
        SmtpServer.Send(mail)
    End Sub

Итак, войдите в свою учетную запись, а затем перейдите к
google.com/settings/security/lesssecureapps


просто включите настройку или Gmail.
см. ниже данное изображение:

enter image description here


У меня есть ранее работающий код, который выдает эту ошибку сейчас. Нет проблем с паролем. Нет необходимости конвертировать сообщение в base64 либо. Получается, мне нужно сделать следующее:

  1. отключить 2-факторную аутентификацию
  2. установить» разрешить менее безопасные приложения » на
  3. войдите в свою учетную запись gmail с производственного сервера
  4. Go здесь а также утвердить логин активность
  5. запустите приложение в производстве сервер

код

    public static void SendEmail(string emailTo, string subject, string body)
    {
        var client = new SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new NetworkCredential("youremail@gmail.com", "secretpassword"),
            EnableSsl = true
        };

        client.Send("youremail@gmail.com", emailTo, subject, body);
    }

отключение 2-факторной аутентификации
Turning off 2-factor authentication

установить» разрешить менее безопасные приложения » на (та же страница, нужно прокрутить вниз)
Allow less secure apps


я попробовал все предложения, найденные здесь, от включения менее безопасных приложений до попытки порта 587… ничего не помогало. Наконец, я просто прокомментировал строку UseDefaultCredentials = false. Все работало, если я не касался этого булева.


Если вы используете gmail.

  • 1-Войдите в свой аккаунт

    2 — обзор этого ссылке

    3-разрешить менее безопасные приложения: ON

наслаждайтесь….


Я действительно посмотрел на много идей, единственное решение было таким образом (работает с разными поставщиками электронной почты):

            try
        {
            ViewProgressbar("Try to connect mail-server...", progressBar1.Value = 20);
            string host = dsProvider.Rows[y]["POP_hostOut"].ToString();
            int port = int.Parse(dsProvider.Rows[y]["POP_portOut"].ToString());  //587
            string[] email = von1.Split('@');
            string userName = (dsProvider.Rows[y]["login"].ToString() == "email[0]@email[1]")? email[0]+"@"+email[1] : email[0];
            string password = layer.getUserPassword(listSender.SelectedValue.ToString());
            SmtpClient client = new SmtpClient(host, port);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            //A idea from MSDN but it not works. You got the "The server response was: 5.5.1 Authentication Required."
            //System.Net.NetworkCredential myCreds = new System.Net.NetworkCredential(userName, password, host);
            //System.Net.CredentialCache cache = new System.Net.CredentialCache();
            //cache.Add(host, port, "NTLM", myCreds);
            ///cache.GetCredential(host, port, "NTLM");   //NTLM
            client.Credentials = new System.Net.NetworkCredential(userName, password);
            client.Host = host;
            client.Port = port;
            client.EnableSsl = true;
            client.Send(message);
            ViewProgressbar();
        }
        catch (SmtpException ex)...

Я подписчик google apps для бизнеса, и я провожу последние пару часов, просто имея дело с этим, даже после того, как все правильные настройки (smtp, порт, enableSSL и т. д.). Вот что сработало для меня и веб-сайтов, которые бросали ошибку 5.5.1 при попытке отправить электронное письмо:

  1. войдите в свой admin.google.com
  2. нажмите Безопасность
  3. Нажмите Basic Настройки
  4. прокрутите до нижней части окна основные настройки, нажмите на ссылку: «Перейти к настройкам для менее безопасных приложений»
  5. выберите опцию #3: принудительный доступ к менее безопасным приложениям для всех пользователей (не рекомендуется)
  6. нажмите «Сохранить» в нижней части окна

после этого мои формы электронной почты с веб-сайта снова работали. Удачи!



комментарий от Томаш Мадейски является то, что фиксированная моя проблема… он говорит что существует баг на SetDefaultCredential, ему говорит:

» проблема в том, что в сеттере UseDefaultCredentials есть этот код: this.транспорт.Учетные данные = значение ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials: (ICredentialsByHost) null; который переопределяет учетные данные, установленные Задатчиком учетных данных. Для меня это похоже на ошибку SmtpClient»

если поставить smtpClient.UseDefaultCredentials = false после установить полномочия… эта строка имеет значение null этих полномочий…



-1

автор: AndroidMechanic — Viral Patel


попробуйте изменить хост, это новый, я получил эту настройку mozilla thunderbird

Host = "smtp.googlemail.com"

это работает для меня


#authentication #oauth-2.0 #outlook #imap #javax.mail.address

Вопрос:

мы пытаемся войти в систему outlook.com в нашем приложении с помощью oauth2.0 мы выполнили регистрацию приложения AAD. Приложение успешно аутентифицирует пользователя и отвечает с помощью access_token, теперь мы хотели прочитать электронные письма с сервера imap, и здесь мы получаем сбой, пожалуйста, попробуйте помочь нам в этом.

Пожалуйста, найдите ниже ошибку, которую мы получаем.

  • ХОРОШО, служба Microsoft Exchange IMAP4 готова. [UABOADIAUABSADAAMQBDAEEAMAAwADYAMgAuAEkATgBEAFAAUgBEADAAMQAuAFAAUgBPAEQALgBPAFUAVABMAE8ATwBLAC4AQwBPAE0A] ВОЗМОЖНОСТЬ A0
  • ВОЗМОЖНОСТЬ IMAP4 IMAP4rev1 АУТЕНТИФИКАЦИЯ=ОБЫЧНАЯ АУТЕНТИФИКАЦИЯ=XOAUTH2 ИДЕНТИФИКАТОР UIDPLUS SASL-IR ОТМЕНЯЕТ ВЫБОР ДОЧЕРНЕГО ЛИТЕРАЛА ПРОСТАИВАЮЩЕГО ПРОСТРАНСТВА ИМЕН A0 ОК ВОЗМОЖНОСТЬ завершена. Отладка IMAPS: аутентификация: обычная отладка IMAPS: для auth: XOAUTH2 debug в IMAPS: protocolConnect login, то host=outlook.office365.com, user=siccsanda@outlook.com, пароль= «отладка» IMAPS: механизм простой отключена по недвижимости: почта.imaps.авт.равнины.отключить отладку IMAPS: механизм входа в систему не поддерживается сервером отладки IMAPS: механизм NTLM не поддерживается сервером аутентификации А1 XOAUTH2 dXNlcj1zaWNjc2FuZGFAb3V0bG9vay5jb20BYXV0aD1CZWFyZXIgRXdCd0E4bDZCQUFVNms3K1hWUXprR3lNdjdWSEIvaDRjSGJKWVJBQUFhbWdZWE81azJ2NEVQYmduSE5BWUcyNENWYXJ4V2dEek9lZ2E2S0J0SGZKcDVkV1hkK3E5T2ExSEJocitIQW1JWVJBRkh6NWxFRWJJRFdGZVF6MGU5U0pRNzZzVnYwUVhXVFFRRUExSktRSmdHdm51Z3QrV2dvd1pJUUxmcVJBQmh2Mm02WWk4bDlWU1FGS1pzV2lpY000blYzWElza0RyYWlWRTNjU2ZMS0tmK09MUDg4OHNCNnVPbzlOWDNXYnZFWUdZTGVMbVpjUG5NOUlrK3MzazhYQWtpOWY2VTl6MGFjUHdKQWRsbk9JZElvNzJQYjhYeXJmVDB6OHpFV2ExRm8xVVpiUHJvdnIrakd1NTJhcjMyaVlZWnpkSDhxaGhZRFRFcTJOQnhOUDVaV1dsbTZQV2lYR2ZhZ05EL2k3RWxDSFJRZ0twdFN2dDMySEpaN3VqRkFEWmdBQUNDYTdqZGVnM3cza1FBSUdpR09YREFaYmdhK3ZDempqeERwT29wZExERTQzaldhbHRVSHJDVk8zS1BSMFFzMzV5SDNTeWNaK0xqTEl1U043VVZheWozUHZWejZ1bDZPdkxkSUozVkhpcjBBbTRxeDlvWjRobnBLRG0yc2Q2akptUWxtVFFHRmhqTjVLN0poSmUyb1VvMzJZNHlrYU1vNFRPQkpxc3ZuOCtja0dCekRHYUdsWjltU0dsZmpJWDdIR29HbnQ4S2NmOEhsTFdnSzhpVWkvOWJoTjV4MnNNSWM0YzhWWlRlUkpJbXNrQUNQbnRoSGoybUNHeXpmRi9qTXkvbnV4VFNOVE0wby9QS045ME00M1VGT3hDSk5MRldiVkkwQ3RzcDNWRGZ6MWVZejdZV1NtLzNtSlhkSk02bkFIeWZRQnFJZTB3Q3A1aU9pU1J2R3pyV0o1WXlVRWNWV1VyRndxQjBQbXFUMEJFeVBOOVhLR0FZQmlFQ2hEanpqS1NjUFRNM29jbEdCQld6V0FNYzF4bUVXTktsSm5Ma0s3N3Z3S2NkYklTa1c1WWdBbU84ZWZrUExIdU16UnpuQ2o3NTQzS0dCOEpFUTlZSUx0TkJQMTZmcjFYR1NnVkFwb2tkUU1wdG1YU2dFd2pJZnozKzgrWDE0MFJqblZaYjdrbzBQNnJsQzNnWkRVdEdoQ3I2Mm15ZzN2U1pZaUt2UzBrVkR2ZDhFbUJ3N1BUZGVlWFZEWXZYc2gycTJMY2NleEVhOXJuSHFra1g4cVVRNWp2U2RvT2JTL3VGM1hZL1VuajlHZUFhbERCdEZvUXhsREkvaU5aeGVoS2FFSDFydE5ncTI2by9oSW1NNzZDb3BwcCtzb0p3dUJQNE5wbDFHY1RQNEdycjFURVkwbGRTTW4zNDdwODE2WEZJWk1FSVJiSEpoekR6VVNIRVQxbjFRbEZyOUhRZlVVSHhCOWtPMWlzVzdEaDdaSFhMSnBBRCtiTHc3SGpuY3JYcHBXdkEydFRzclNWVVkwSDhJS2lpU0hBZz09AQE=
    A1 NO AUTHENTICATE failed.

Пожалуйста, найдите код для подключения:

  properties.put("mail.imaps.host", "outlook.office365.com");
        properties.put("incomingHost", "outlook.office365.com");
        properties.put("outgoingHost", "smtp.office365.com");
        properties.put("mail.imaps.ssl.enable", "true");
        //properties.put("mail.imaps.sasl.enable", "true");
        properties.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
       // properties.put("mail.imap.auth.login.disable", "true");
        properties.put("mail.imaps.auth.plain.disable", "true");
        //properties.put("mail.imaps.auth.plain.disable", "true");
        properties.put("mail.debug", "true");
        properties.put("mail.debug.auth", "true");
        properties.setProperty("mail.imaps.ssl.trust", "*");
        properties.setProperty("mail.smtp.starttls.enable","true");
       
        this.store = session.getStore("imaps");
     store.connect("outlook.office365.com", "abc@outlook.com", "access_token");
 

Ответ №1:

Я также борюсь с XOAUTH. В своем коде я задаю свойства:

 Mail property mail.imaps.auth.plain.disable: true
Mail property mail.imaps.auth.mechanisms: XOAUTH2
Mail property mail.imaps.port: 993
Mail property mail.store.protocol: imaps
Mail property mail.imaps.ssl.enable: true
Mail property mail.imaps.partialfetch: false
Mail property mail.mime.decodetext.strict: false
Mail property mail.imaps.peek: true
Mail property mail.mime.charset: UTF-8
 

что привело (по крайней мере) к входу в систему XOAUTH

 DEBUG IMAPS: AUTHENTICATE XOAUTH2 command result: A1 NO AUTHENTICATE failed.
 

  • Xnview ошибка при открытии файла jpg
  • Xmyey код ошибки 100000
  • Xmrig cuda dll ошибка
  • Xmodgames ошибка при подключении пожалуйста повторите попытку
  • Xmlстрока ошибка преобразования данных xml