Exchange Web Service API and 401 unauthorized exception
Solution 1
Try changing this:
exchangeService.Credentials = new WebCredentials("user@domain", "pwd", "domain");
into this:
exchangeService.Credentials = new WebCredentials("user", "pwd", "domain");
Sometime the Login credentials depends on how Exchange/Active Directory it's configured. It could be user@domain or domain\user
Solution 2
In my case, I needed to add to the EWS Virtual Directory under the IIS site the list of allowed URLs.
Go to the IIS management, click the EWS node, under the Default Web Site, then double-click the Request Filtering.
Go to the URL tab, and on the right, click Allow URL.
Enter the URLs by which you will invoke the service, e.g. example.com/ews/ or server.example.com/ews/
In addition, related to similar issues, I needed to add all hosts (*) to the winrm trusted host (by default it had only the local IP listed).
Related videos on Youtube
GwenGuts
Updated on March 18, 2021Comments
-
GwenGuts about 3 years
When I try sending email using the EWS API, I get the following error: (in
message.Send();
)The request failed. The remote server returned an error: (401) Unauthorized.
My code is the following:
ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2007_SP1); //WebService Uri try { exchangeService.Url = new Uri("https://exchangeserver/ews/exchange.asmx"); } catch (Exception ex) { throw new Exception(string.Format("WebService Uri:" + ex)); } //Credentials try { exchangeService.Credentials = new WebCredentials("user@domain", "pwd", "domain"); } catch (Exception ex) { throw new Exception(string.Format("Credentials:" + ex)); } //Send a mail try { EmailMessage message = new EmailMessage(exchangeService); message.Subject = "Test"; message.Body = "Test"; message.ToRecipients.Add("destination@domain"); message.Save(); message.Send(); } catch (Exception ex) { throw ex; }
I read other posts on this site concerning this issue but they couldn't resolve my issue.
-
RenniePet over 6 yearsIn a situation where the EWS connection previously worked, and then isn't working, it may be something as simple as the password having expired, and needs to be changed.
-
Mohamme5d almost 2 yearshave you find solution for this issue ?
-
-
jtimperley over 10 yearsOurs worked locally as 'domain\username', however external I had to split the domain and user name.
-
Coxy over 8 yearsI actually had to switch my username to a fully qualified email address, ie.
[email protected]
, in order to get it to work. Specifying the AD domain or not (the third argument of theWebCredential
constructor) made no difference for me. -
Avishekh Bharati almost 3 yearsfor the individual email, I can do it. How about for all the emails within the organization? Scenario: User should be able to enter username and password and be able to retrieve emails in my application.