通过EWS API连接到Office 365

我在我的控制台应用程序中使用EWS API来处理邮箱项目,我的连接脚本看起来像

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.UseDefaultCredentials = true; service.AutodiscoverUrl("emailService@domain.com"); 

但我发现我的电子邮件帐户已移至Office 365云。 我该如何更改身份validation?

我找到了EWS服务url

  service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); 

但我不知道如何使用它。

谢谢

您可以使用以下代码连接到Office 365上的EWS:

 ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.Credentials = new WebCredentials("emailService@domain.com", "password"); service.AutodiscoverUrl("emailService@domain.com", RedirectionUrlValidationCallback); 

您需要为AutodiscoveryUrl函数定义一个回调函数,如下所示:

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

我知道这是一个相当古老的解决方案,但它对我来说仍然非常有帮助。 我有一些工具可以使用“普通”网络版本的Exchange,但到目前为止我的Exchange Online测试失败了(我收到了“无法找到自动发现服务”等错误)。

这里必不可少的是使用WebCredentials而不是NetworkCredential和电子邮件地址而不是用户名。