简体   繁体   中英

Exchange Web Service API and 401 unauthorized exception

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.

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\u003c/i>

In my case, I needed to add to the EWS Virtual Directory under the IIS site the list of allowed URLs.

  1. Go to the IIS management, click the EWS node, under the Default Web Site, then double-click the Request Filtering.

  2. Go to the URL tab, and on the right, click Allow URL.

  3. Enter the URLs by which you will invoke the service, eg 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).

此问题可能导致 Microsoft Office 365 提供的双向身份验证。最好创建应用程序密码并传递该密码,而不是 Outlook 密码。

exchangeService.Credentials = new WebCredentials("email", "app-pwd");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM