Connection to Office 365 by EWS API

There appear to have been a few changes in EWS connection to office365 in regards to security, causing Matt's answer to not work for me.

What did work is the following:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1)
{
     Credentials = new WebCredentials("user", "password", "domain"),
     Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx")
};

Important notes:

  • AutodiscoverUrl did not complete successfully, it failed to discover the URL every time

  • user must be the full email address of the user.

  • domain is the NetBIOS domain name, meaning it is only the domain name. You can find the domain in the Microsoft 365 admin center under Settings -> Domains. The easiest way is to find the fallback domain in the form of domain.onmicrosoft.com. Take only the domain part.

  • The user must be a Microsoft 365 admin

  • Any change in one of these parameters caused an Unauthorized exception.


You can use the code below to connect to the EWS on office 365:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);

service.Credentials = new WebCredentials("[email protected]", "password");
service.AutodiscoverUrl("[email protected]", RedirectionUrlValidationCallback);

You need define one callback function for the AutodiscoveryUrl function, like this:

private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
    // The default for the validation callback is to reject the URL.
    bool result = false;

    Uri redirectionUri = new Uri(redirectionUrl);

    // Validate the contents of the redirection URL. In this simple validation
    // callback, the redirection URL is considered valid if it is using HTTPS
    // to encrypt the authentication credentials. 
    if (redirectionUri.Scheme == "https")
    {
        result = true;
    }
    return result;
}