无法通过具有授权权限的Microsoft Graph API发送电子邮件 [英] Unable to send email via Microsoft Graph API with Delegated Permission

查看:77
本文介绍了无法通过具有授权权限的Microsoft Graph API发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个C#控制台应用程序,以使用Microsoft Graph API发送电子邮件.添加Mail.Send 应用权限后,它可以正常工作.但是,由于公司的要求,我被要求使用Mail.Send来发送 Delegated 权限,但是在该权限下,我认为它没有用,并且出现了以下错误:

添加Mail.Send Delegated 权限后,我是否应该考虑采取任何步骤以使此工作正常进行?

这是我的代码:

 静态void Main(string [] args){//Azure AD APP字符串clientId =<< client key Here>" ;;字符串tenantID =<此处的租户密钥";字符串clientSecret =<此处的客户机密";Task< GraphServiceClient>callTask​​ = Task.Run(()=> SendEmail(clientId,tenantID,clientSecret));//等待完成callTask​​.Wait();//获得结果var astr = callTask​​;}公共静态异步Task< GraphServiceClient>SendEmail(字符串clientId,字符串tenantID,字符串clientSecret){var secretClientApplication =机密ClientApplicationBuilder.Create(客户编号).WithTenantId(tenantID).WithClientSecret(clientSecret).建造();var authProvider = new ClientCredentialProvider(confidentialClientApplication);var graphClient = new GraphServiceClient(authProvider);var message =新消息{主题=主题,正文=新的ItemBody{ContentType = BodyType.Text,内容=内容},ToRecipients = new List< Recipient>(){新收件人{电子邮件地址=新的电子邮件地址{地址=收件人地址}}}};var saveToSentItems = true;等待_graphClient.Users [< userprincipalname>].SendMail(消息,saveToSentItems).要求().PostAsync();返回graphClient;} 

更新:

基于以下答案,我更新了代码,如下所示:

  var publicClientApplication = PublicClientApplicationBuilder.Create(< client-id>").WithTenantId(< tenant-id>").建造();var authProvider =新的UsernamePasswordProvider(publicClientApplication); 

  var secureString = new NetworkCredential(,",< password",)).用户我=等待graphClient.Me.Request().WithUsernamePassword(< username>",secureString).GetAsync(); 

我启用了允许公共客户端流量"解决异常.

现在我看到另一个异常:没有足够的权限来完成操作.

我想念什么?

更新:目前,我看到此异常,并且代码中没有任何更改:

解决方案

您提供的代码显示您使用

I created a C# console application to send email using Microsoft Graph API. On adding Mail.Send Application Permission, it works fine. But, because of company requirements, I was asked to use Mail.Send Delegated Permission instead and with that permission I don't see it working and I see this error:

Are there any steps I should consider doing after adding Mail.Send Delegated Permission in order to get this working?

Here is my code:

    static void Main(string[] args)
    {
        // Azure AD APP
        string clientId = "<client Key Here>";
        string tenantID = "<tenant key here>";
        string clientSecret = "<client secret here>";

        Task<GraphServiceClient> callTask = Task.Run(() => SendEmail(clientId, tenantID, clientSecret));
        // Wait for it to finish
        callTask.Wait();
        // Get the result
        var astr = callTask;
    }

    public static async Task<GraphServiceClient> SendEmail(string clientId, string tenantID, string clientSecret)
    {

        var confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantID)
            .WithClientSecret(clientSecret)
            .Build();

        var authProvider = new ClientCredentialProvider(confidentialClientApplication);       

        var graphClient = new GraphServiceClient(authProvider);

        var message = new Message
            {
                Subject = subject,
                Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = content
                },
                ToRecipients = new List<Recipient>()
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress { Address = recipientAddress }
                    }
                }
            };

         var saveToSentItems = true;

         await _graphClient.Users[<userprincipalname>]
                                .SendMail(message, saveToSentItems)
                                .Request()
                                .PostAsync();

        return graphClient;

    }

UPDATE:

Based on below answer, I updated code as follows:

var publicClientApplication = PublicClientApplicationBuilder
            .Create("<client-id>")
            .WithTenantId("<tenant-id>")
            .Build();

            var authProvider = new UsernamePasswordProvider(publicClientApplication);

var secureString = new NetworkCredential("", "<password>").SecurePassword;

User me = await graphClient.Me.Request()
                .WithUsernamePassword("<username>", secureString)
                .GetAsync();

I enabled "Allow public client flows" to fix an exception.

And now I see another exception: Insufficient privileges to complete the operation.

What am I missing?

UPDATE: Currently I see this exception with no changes in the code:

解决方案

The code you provided shows you use client credential flow to do the authentication. When you use Mail.Send Application permission, use client credential flow is ok. But if you use Mail.Send Delegated permission, we can not use client credential. You should use username/password flow to do authentication.

=================================Update===================================

Below is my code:

using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Security;

namespace ConsoleApp34
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var publicClientApplication = PublicClientApplicationBuilder
            .Create("client id")
            .WithTenantId("tenant id")
            .Build();

            string[] scopes = new string[] { "mail.send" };

            UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);

            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            var message = new Message
            {
                Subject = "Meet for lunch?",
                Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = "The new cafeteria is open."
                },
                ToRecipients = new List<Recipient>()
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = "to email address"
                        }
                    }
                }
            };

            var securePassword = new SecureString();
            foreach (char c in "your password")
                securePassword.AppendChar(c);

            var saveToSentItems = true;

            await graphClient.Me
                    .SendMail(message, saveToSentItems)
                    .Request().WithUsernamePassword("your email", securePassword)
                    .PostAsync();
        }
    }
}

The reason for your error message Insufficient privileges to complete the operation is you use the code:

User me = await graphClient.Me.Request()
                .WithUsernamePassword("<username>", secureString)
                .GetAsync();

This code is used to get the user(me)'s information but not send email, you haven't added the permission to the app. So it will show Insufficient privileges to complete the operation. Please remove this code and use the code block in my code instead:

await graphClient.Me.SendMail(message, saveToSentItems)
                    .Request().WithUsernamePassword("your email", securePassword)
                    .PostAsync();

==============================Update2====================================

这篇关于无法通过具有授权权限的Microsoft Graph API发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆