[英]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.