Search code examples
c#exchange-serverexchangewebservices

Authentication against EWS stopped working


The following code worked at last at the 12. Oct. 2022. Today I started it and it throws an error 401.

Has something changed on Microsoft side or what could have happened and how do I get it working again?

static void Main(string[] args)
    {
        ExchangeService _service;
        _service = new ExchangeService
        {
            Credentials = new WebCredentials(myusername,mypassword)
            //Credentials = new NetworkCredential(myusername,mypassword)
        };
        string serviceURI = "https://outlook.office365.com/EWS/Exchange.asmx";
        _service.Url = new Uri(serviceURI);
        EmailMessage message = new EmailMessage(_service);
        message.Subject = "Test email";
        message.Body = "<h1>Test-E-Mail</h1>";
        message.Body.BodyType = BodyType.HTML;
        //message.Attachments.AddFileAttachment(reportname);
        message.ToRecipients.Add(recipient);
        message.SendAndSaveCopy();
    }

Thrown error at row "SendAndSaveCopy":

Microsoft.Exchange.WebServices.Data.ServiceRequestException: 'The request failed. The remote server returned an error: (401) .'


Solution

  • As announced in September 2021, Microsoft began permanently disabling basic authentication (as you are using here) for EWS in Exchange Online starting 1st October 2022. You will therefore need to migrate to using OAuth 2.0 authentication. There is some documentation on using OAuth 2.0 to authenticate to EWS here.