Microsoft Graph Api 邮件发送对象引用未设置为对象错误的实例

Microsoft Graph Api Mail Send Object reference not set to an instance of an object error

提问人:Esra 提问时间:10/31/2023 最后编辑:Esra 更新时间:10/31/2023 访问量:64

问:

我正在尝试使用软件中的图形 API 发送电子邮件。我发送的电子邮件的消息部分已满,那里似乎没有任何问题。但是在发送时,它会给出错误“对象引用未设置为对象的实例”。传递 Task.Delay 方法后,出现此错误。我做错了什么?我想不通。 此代码:

try
{

  
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;


    //var url = GetMailConfig(configGroup: "EWS", configName: "EwsUrl");
    var username = GetMailConfig(configGroup: "EWS", configName: "Email");
    var password = GetMailConfig(configGroup: "EWS", configName: "Password");
    var fromAddress = GetMailConfig(configGroup: "SMTP", configName: "From");
    //var traceEnabled = GetMailConfig(configGroup: "EWS", configName: "TraceEnabled");
    var tenantId = GetMailConfig(configGroup: "EWS", configName: "TenantId");
    var clientId = GetMailConfig(configGroup: "EWS", configName: "ClientId");
    var access_token = "";
    var redirect_uri = "https://example.example.com/";
    var clienSecretId = "This is secret key";
    //var scopes = new[] { "https://outlook.office365.com/SMTP.Send" };
    var scopes = new[] {"https://graph.microsoft.com/.default" };



    var pca = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithClientSecret(clienSecretId)
    .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
    .Build();



    var authProvider = new DelegateAuthenticationProvider(async (request) =>
    {

        try
        {


            var result = await pca.AcquireTokenForClient(scopes).ExecuteAsync();

            

            request.Headers.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
        }
        catch (Exception exp)
        {
            
        }

    });


    GraphServiceClient graphClient = new GraphServiceClient(authProvider);

    var message = new Message
    {
        Subject = mailTemplate.Subject,
        From = new Recipient() { EmailAddress = new Microsoft.Graph.EmailAddress { Address = "[email protected]" } },
        Body = new ItemBody
        {
            ContentType = Microsoft.Graph.BodyType.Html,
            Content = mailTemplate.Body
        },

    };

    MailMessage mail = new MailMessage();


    var attachments = new MessageAttachmentsCollectionPage();

    if (mailTemplate.Cc != null && mailTemplate.Cc.Any())
        message.CcRecipients = mailTemplate.Cc.Select(x => new Recipient()
        {
            EmailAddress = new Microsoft.Graph.EmailAddress
            {
                Address = x
            }
        });



    if (mailTemplate.To != null && mailTemplate.To.Any())
        message.ToRecipients = mailTemplate.To.Select(x => new Recipient()
        {
            EmailAddress = new Microsoft.Graph.EmailAddress
            {
                Address = x
            }
        });

    var saveToSentItems = false;


    System.Threading.Tasks.Task.Run(async () =>
    {
        try
        {
            
            await Task.Delay(TimeSpan.FromSeconds(5));
            await graphClient.Me
           .SendMail(message, saveToSentItems)
           .Request()
           .PostAsync();
        }
        catch (Exception ex)
        {

            
        }

    });


}
catch (Exception exp)
{

    isSentMailSuccess = false;
}
return isSentMailSuccess;

 
            await Task.Delay(TimeSpan.FromSeconds(5));
            await graphClient.Me
           .SendMail(message, saveToSentItems)
           .Request()
           .PostAsync();

此代码有例外。

我一行一行地检查代码行,但找不到方法。

C# asp.net .NET 可视化工作室 microsoft-graph-api

评论

0赞 gunr2171 10/31/2023
哪条线会引发异常?哪个对象为 null?你能编辑你的帖子来缩短你的代码示例吗?请参阅最小可重现示例
0赞 jdweng 10/31/2023
删除 await。Delay 不是返回对象的异步方法。等待需要返回一些东西才能继续。
0赞 Esra 10/31/2023
@gunr2171我添加了异常行
0赞 user2250152 10/31/2023
请分享堆栈跟踪。尝试调试代码,以确保 graphClient 不为 null。
0赞 wenbingeng-MSFT 10/31/2023
如果使用图形 API 发送电子邮件,则需要确保具有必要的权限,并且消息对象配置正确。使用 graphClient.Me.SendMail(...),它代表当前经过身份验证的用户发送电子邮件。因此,您必须确保您具有必要的权限,并且您的消息对象正确填充了必填字段

答:

1赞 user2250152 10/31/2023 #1

使用具有客户端 ID 和客户端凭据的身份验证时,无法调用终结点 ()。/megraphClient.Me.xxx

您未以任何用户的身份进行身份验证。

因此,将代码更改为

await graphClient.Users["{user-id}"]
           .SendMail(message, saveToSentItems)
           .Request()
           .PostAsync();

或更改身份验证以代表用户获取访问权限

堆栈跟踪也很有用,不清楚到底什么是空的并引发异常。