Connection to Office 365 by EWS API

Solution 1:

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;
}

Solution 2:

There appears 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")
};

Importat 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 exeption.

Solution 3:

I know this is a fairly old solution, but it was still very helpful to me. I have a few tools that worked with the "normal" network version of Exchange, but so far my tests with Exchange Online failed (i got errors like "The Autodiscover service couldn't be located", etc).

Essential here is to use WebCredentials instead of NetworkCredential and a e-mailaddress instead of a username.

Solution 4:

You cannot use basic authentication (username and password) in your EWS application to connect to Office/Microsoft 365 now. Microsoft no longer supports basic authentication in EWS for Exchange Online. You are advised to use OAuth2.0 to get a token and use the same in your EWS client to connect to Office 365.

For this you will have to register your application in Azure AD to use client credential flow. I did a POC on this using console application. enter image description here

enter image description here

Here's the link to GitHub repository for source code and documentation.