0

Scenario: Console application needs to send an email from defined mailbox. All setup in Azure is done and application has access and all works well in Postman.

Question is how to do the same with Microsoft libraries - especially with GraphServiceClient.

Note: example is not showing message body as it is not relevant for the question.

Raw request

POST https://graph.microsoft.com/v1.0/users/<email-address>/sendMail

.NET code

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
    .WithClientSecret(secret) 
    .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);

await graphClient.Me
    .SendMail(message, saveToSentItems)
    .Request()
    .PostAsync();

1 Answer 1

1

I've done this in c#.NET - here's some code, which has been refactored/simplified on the fly (so no guarantees) to just show what you need. Obviously you'll need to replace the magic strings with your own values.

var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(async request =>
{
    var authContext = new AuthenticationContext("https://login.microsoftonline.com/GUID");
    var credential = new ClientCredential("GUID", "P@55w0rd");
    var authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credential);

    request.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
}));

var user = graphServiceClient.Users["[email protected]"];
var message = GetMailMessage(); // not relevant to question
await user.SendMail(message).Request().PostAsync(new CancellationTokenSource(new TimeSpan(0, 0, 30)).Token);
Sign up to request clarification or add additional context in comments.

1 Comment

Key for me was to realize that the graphServiceClient.Users[email] gives me the same options as graphServiceClient.Me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.