Search code examples
c#impersonationexchangewebservices

Exchange Impersonation in Service Account: Autodiscover service couldn't be located


Sending a simple email through ews is working as intended - from my account to my account:

ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010);
ews.AutodiscoverUrl("[email protected]");
EmailMessage email = new EmailMessage(ews);
email.ToRecipients.Add("[email protected]");
email.Subject = "HelloWorld";
email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");
email.Send();

Simply trying impersonation, it is also working as intended - in the last line, it returns the error that I am not allowed to impersonate:

ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010);
ews.AutodiscoverUrl("[email protected]");
ews.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");
EmailMessage email = new EmailMessage(ews);
email.ToRecipients.Add("[email protected]");
email.Subject = "HelloWorld";
email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");
email.Send();

Now I try to login with my application service account instead:

ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010);
ews.Credentials = new NetworkCredential("service", "1234", "mydomain.com");
//ews.Credentials = new WebCredentials("service", "1234");
ews.AutodiscoverUrl("[email protected]");
//ews.AutodiscoverUrl("[email protected]");
ews.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");
EmailMessage email = new EmailMessage(ews);
email.ToRecipients.Add("[email protected]");
email.Subject = "HelloWorld";
email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");
email.Send();

But here it throws an error in the autodiscover line: "AutodiscoverLocalException: The Autodiscover service couldn't be located."

The service account is set up in AD and Exchange, with correct password and smtp address.

Why isn't it working? How can I check what's causing that error?


Solution

  • I solved the problem, and guess what the problem is: it's the user account.

    EWS uses the given credentials to authenticate itself for access to the Autodiscover service at

    http://mydomain/AutoDiscover/AutoDiscover.xml
    

    The credentials were correct, but it seems that for accounts set to "user has to change password on first login", access to the autodiscover service is denied. I changed that setting in AD and now it works.