简体   繁体   English

读取 EWS 文件夹时出现 Microsoft.Exchange.WebServices.Data.ServiceRequestException

[英]Microsoft.Exchange.WebServices.Data.ServiceRequestException at reading the EWS folders

I'm a newbie to C# development我是 C# 开发的新手

I'm trying to migrate the EWS authentication from basic authentication to OAuth2 authentication.我正在尝试将 EWS 身份验证从基本身份验证迁移到 OAuth2 身份验证。

#Implementation #执行

using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Identity.Client;



namespace DataLoadLibrary.Email
{
    public class OAuthTokenProviders
    {


        public static async Task<OAuthTokenProviders> Create()
        {
            var myClass = new OAuthTokenProviders();
            await myClass.Initialize();
            return myClass;
        }

        private OAuthTokenProviders()
        {
            Console.WriteLine("TESTING INSIDE CONSTRUCT");

        }


        
        private async System.Threading.Tasks.Task Initialize()
        {
            Console.WriteLine("TESTING");
            // Using Microsoft.Identity.Client
            var cca = ConfidentialClientApplicationBuilder
                .Create("")      //client Id
                .WithClientSecret("")
                .WithTenantId("")
                .Build();
            var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
            try
            {
                // Get token
                var authResult = await cca.AcquireTokenForClient(ewsScopes)
                    .ExecuteAsync();
                // Configure the ExchangeService with the access token
                var ewsClient = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
                ewsClient.ImpersonatedUserId =
                    new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "");
                //Include x-anchormailbox header
                ewsClient.HttpHeaders.Add("X-AnchorMailbox", "");
                // Make an EWS call to list folders on exhange online

                var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
                foreach (var folder in folders)
                {
                    Console.WriteLine($"Folder: {folder.DisplayName}");
                }
                // Make an EWS call to read 50 emails (last 5 days) from Inbox folder
                TimeSpan ts = new TimeSpan(-60, 0, 0, 0);
                DateTime date = DateTime.Now.Add(ts);
                SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
                var findResults = ewsClient.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));
                foreach (var mailItem in findResults)
                {
                    Console.WriteLine($"Subject: {mailItem.Subject}");
                }
                EmailMessage email = new EmailMessage(ewsClient);
                email.ToRecipients.Add("");
                email.Subject = "HelloWorld";
                email.Body = new MessageBody("This is a test email using MS Exchg we services");
                email.Send();
            }
            catch (MsalException ex)
            {
                Console.WriteLine($"Error acquiring access token: {ex}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex}");
            }
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine("Hit any key to exit...");
                Console.ReadKey();
            }
        }


    }
}

Using the above implementation am able to get the access token successfully.使用上述实现能够成功获取访问令牌。 However when am listing the folder in the mailbox, getting below exceptions但是,当我列出邮箱中的文件夹时,出现以下异常

Microsoft.Exchange.WebServices.Data.ServiceRequestException
  HResult=0x80131500
  Message=The request failed. The underlying connection was closed: An unexpected error occurred on a send.
  Source=Microsoft.Exchange.WebServices
  StackTrace:
   at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request)
   at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request)
   at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute()
   at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalFindFolders(IEnumerable`1 parentFolderIds, SearchFilter searchFilter, FolderView view, ServiceErrorHandling errorHandlingMode)
   at Microsoft.Exchange.WebServices.Data.ExchangeService.FindFolders(FolderId parentFolderId, FolderView view)
   at Microsoft.Exchange.WebServices.Data.ExchangeService.FindFolders(WellKnownFolderName parentFolderName, FolderView view)
   at DataLoadLibrary.Email.OAuthTokenProviders.<Initialize>d__2.MoveNext() in C:\Users\path\to\file\DataLoadLibrary\Email\OAuthTokenProviders.cs:line 51

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
WebException: The underlying connection was closed: An unexpected error occurred on a send.

Inner Exception 2:
IOException: Authentication failed because the remote party has closed the transport stream.

I would want to know how to solve the exception.我想知道如何解决异常。 Thanks in Advance提前致谢

Message=The request failed. Message=请求失败。 The underlying connection was closed: An unexpected error occurred on a send.基础连接已关闭:发送时发生意外错误。

That error is generally related to TLS as Office365 require at least TLS 1.2 to be used.该错误通常与 TLS 有关,因为 Office365 要求至少使用 TLS 1.2。 Generally the best way of solving this is through the following reg entry https://learn.microsoft.com/en-us/officeonlineserver/enable-tls-1-1-and-tls-1-2-support-in-office-online-server#enable-strong-cryptography-in.net-framework-45-or-higher this will mean .net will use the strongest version available.通常解决此问题的最佳方法是通过以下注册条目https://learn.microsoft.com/en-us/officeonlineserver/enable-tls-1-1-and-tls-1-2-support-in-office -online-server#enable-strong-cryptography-in.net-framework-45-or-higher这意味着 .net 将使用可用的最强版本。 Otherwise you can force it in the code using否则你可以在代码中强制使用

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 子类化Microsoft.Exchange.WebServices.Data.Item - Subclassing Microsoft.Exchange.WebServices.Data.Item Exchange-Microsoft.Exchange.WebServices.Data.Recurrence.YearlyPattern中缺少时间间隔 - Exchange - Interval is missing in Microsoft.Exchange.WebServices.Data.Recurrence.YearlyPattern 在Universal App中使用Exchange WebServices-EWS - Using Exchange WebServices - EWS - in Universal App Microsoft.Exchange.WebServices.Data.ServiceResponseException:无法访问帐户或邮箱 - Microsoft.Exchange.WebServices.Data.ServiceResponseException: Unable to access an account or mailbox 在Microsoft.Exchange.WebServices.Data.emailmessage.culture中发送xml - sending xml in Microsoft.Exchange.WebServices.Data.emailmessage.culture 如何使用 Microsoft.Exchange.WebServices? - How to use Microsoft.Exchange.WebServices? Microsoft Exchange WebServices约会IsRecurring&AppointmentType - Microsoft Exchange WebServices Appointment IsRecurring & AppointmentType 打开流订阅时EWS ServiceRequestException - EWS ServiceRequestException when opening Streaming Subscription 使用Microsoft.Exchange.WebServices的SSIS脚本任务 - SSIS Script Task with Microsoft.Exchange.WebServices 使用EWS在Exchange服务器上读取自定义Task.itemClass中的所有数据 - Reading all data in custom Task.itemClass on Exchange server using EWS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM