Microsoft.Exchange.WebServices.Data.ServiceRequestException 在读取 EWS 文件夹

Microsoft.Exchange.WebServices.Data.ServiceRequestException at reading the EWS folders

我是 C# 开发的新手

我正在尝试将 EWS 身份验证从基本身份验证迁移到 OAuth2 身份验证。

#实施

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


    }
}

使用上面的实现能够成功获取访问令牌。但是,当我列出邮箱中的文件夹时,出现以下异常

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.

我想知道如何解决异常。提前致谢

Message=The request failed. The underlying connection was closed: An unexpected error occurred on a send.

该错误通常与 TLS 有关,因为 Office365 要求至少使用 TLS 1.2。通常解决此问题的最佳方法是通过以下注册条目 https://docs.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 将使用可用的最强版本。否则你可以在代码中强制使用

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