使用Microsoft.Graph发邮件触发ODataErrors.ODataError错误求助
我在使用Microsoft.Graph发送邮件时,遇到了ODataErrors.ODataError错误。我推测可能是Azure AD配置存在遗漏,但已检查租户ID、API权限等关键项。
以下是我的代码:
public async Task<string> SendEmail() { string tenantId = "0XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX3"; string clientId = "cXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXb"; string objectId = "4XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXa"; string clientSecret = "tXXXX~XXXX~XXXXXXXXXXXXXXXXXXXXXXXXXXXXR"; var options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud }; var creds = new ClientSecretCredential(tenantId, clientId, clientSecret, options); string[] scopes = new[] { "https://graph.microsoft.com/.default" }; var graphClient = new GraphServiceClient(creds, scopes ); var message = new Message() { Subject = "My subject", Body = new ItemBody { ContentType = BodyType.Html, Content = "My content" }, ToRecipients = new List<Recipient>() { new Recipient { EmailAddress = new EmailAddress { Address = "My@Email.com" } } } }; var body = new SendMailPostRequestBody(); body.Message = message; body.SaveToSentItems = false; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; try { await graphClient.Users[objectId].SendMail.PostAsync(body); } catch (Exception ex) { return ex.ToString(); } return null; }
在Panagiotis的帮助下,我修复了一些低级错误,但仍卡在此问题上。
- 更新:我移除了解决方案中所有引用和NuGet包,再逐一重新添加,耗时数小时后问题依旧。未指定TLS1.2时会出现426错误;指定TLS1.2后则触发ODataErrors.ODataError错误。开发环境为Visual Studio 2019,所有项目基于.NET Framework 4.7.2。
- 更新2:我在Visual Studio 2022中创建了一个目标框架为.NET 7.0的空白项目,无需显式指定TLS版本,但仍出现如下错误:
Microsoft.Graph.Models.ODataErrors.ODataError: Exception of type 'Microsoft.Graph.Models.ODataErrors.ODataError' was thrown.
at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.ThrowIfFailedResponse(HttpResponseMessage response, Dictionary2 errorMapping, Activity activityForAttributes) at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendNoContentAsync(RequestInformation requestInfo, Dictionary2 errorMapping, CancellationToken cancellationToken)
at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendNoContentAsync(RequestInformation requestInfo, Dictionary2 errorMapping, CancellationToken cancellationToken) at Microsoft.Graph.Users.Item.SendMail.SendMailRequestBuilder.PostAsync(SendMailPostRequestBody body, Action1 requestConfiguration, CancellationToken cancellationToken)
at ConsoleApp.GraphHelper.SendEmail() in C:\ConsoleApp\ConsoleApp\GraphHelper.cs:line 53
希望能得到排查此问题的技术帮助。
内容的提问来源于stack exchange,提问作者Luke Wage

