Отправка почты с помощью приложения-демона - PullRequest
0 голосов
/ 30 января 2020

У меня проблемы с отправкой электронной почты из приложения демона. Я могу получить токен с помощью потока учетных данных клиента, но не могу отправить электронное письмо с помощью Microsoft Graph API. Я получаю следующую ошибку:

    Code: BadRequest
    Message: Found a function 'microsoft.graph.sendMail' on an open property. Functions on open properties are not supported.
    Inner error:
    AdditionalData:
       request-id: e2e3bb60-2212-4c99-8858-d109aaf4f1cd
       date: 2020-01-30T11:18:21
    ClientRequestId: e2e3bb60-2212-4c99-8858-d109aaf4f1cd
}

Ниже приведена кодировка для отправки электронной почты через Microsoft Graph.

private readonly IClientCredentialProvider _clientCredentialProvider;

        public MailTransmitter()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); // contains the tenantId, clientSecret and clientId
            _clientCredentialProvider = new ClientCredentialProvider(config);
        }

        public async Task<bool> SendMail(List<UserEntitlement> sortedListByLastAccessDate)
        {
            //GraphServiceClient graphClient = new GraphServiceClient(_clientCredentialProvider.GetAuthorizationCodeProvider());
            var result = await _clientCredentialProvider.GetClientToken(); // Get token using Client Credentials flow
            var accessToken = result.AccessToken;


            //should I pass the URL to the graphServiceClient like below? Is the URL right?
            var graphServiceClient = new GraphServiceClient("https://graph.microsoft.com/v1.0/0a181b4b-a2fb-4e38-b23b-2c72adc882f2/users/c26d8491-82f8-4f08-990e-35a73ad61ede/memberOf", new DelegateAuthenticationProvider(async (requestMessage) => {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            }));

            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 = "Bla@hotmail.com"
                        }
                    }
                },

                From = new Recipient
                {
                    EmailAddress = new EmailAddress { 
                        Address = "bla.bla@test.nl"
                    }
                }
            };

            var saveToSentItems = false;

            //Error occurs here
            await graphServiceClient.Users["c26d8491-82f8-4f08-990e-35a73ad61ede"]
                .SendMail(message, saveToSentItems)
                .Request()
                .PostAsync();

            return true;
        }

Если вам интересно, как я использовал поток учетных данных клиента, взгляните на: https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/1-Call-MSGraph/daemon-console.

В чем именно проблема?

Заранее спасибо!

1 Ответ

0 голосов
/ 30 января 2020

Указанная ошибка возникает, поскольку для GraphServiceClient предоставлен неверный URL-адрес; ожидается, что первый аргумент будет service root url :

public GraphServiceClient(string baseUrl,IAuthenticationProvider authenticationProvider,IHttpProvider httpProvider = null)

в случае Microsoft Graph API, служба root URL состоит из:

  • https://graph.microsoft.com - это конечная точка API-интерфейса Microsoft Graph.
  • {version} - версия целевой службы, например, v1.0 или бета.

, например, https://graph.microsoft.com/v1.0. Для получения подробной информации см. Обращение в Microsoft Graph API

Пример

var app = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri(authority))
            .Build();

var scopes = new string[] {"https://graph.microsoft.com/.default"};
        var result = await app.AcquireTokenForClient(scopes)
            .ExecuteAsync();

var client = new GraphServiceClient(
                "https://graph.microsoft.com/v1.0",
                new DelegateAuthenticationProvider(async (requestMessage) =>
                {
                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", result.AccessToken);
                }));

или через поставщика учетных данных клиента материя:

var app = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri(authority))
            .Build();



var authProvider = new ClientCredentialProvider(app);
var client = new GraphServiceClient(authProvider);

Пререквизиты: требуется Microsoft.Graph.Auth пакет

...