C# code to to send emails using Microsoft Graph API

Jatinder Singh
3 min readOct 12, 2020

--

This is part 3 of the series on how to send Emails using Graph API. The first 2 parts focus solely on the configuration in the Microsoft Azure. This article focuses on the actual C# code. You can also send email using Postman (which I will publish separately) but that will also require the configuration settings described in the first 2 articles of this series. Check the first 2 steps below:

First step of this series

Second step of this series

You need to write the following code to get Azure credentials required to make API calls

  • Add the packages Microsoft.Graph and Microsoft.Graph.Auth (This is in preview in .Net Core)
  • Add the following namespaces
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
  • Copy the TenantId, ClientId, Client Secret from the 1st step and paste the values in the following code
string tenantId = "Your tenantId copied from 1st step";
string clientId = "Your clientid copied from 1st step";
string clientSecret = "Your client secret copied from 1st step";
string userId ="User Object Id or GUID copied from Step 2"//The following scope is required to acquire the token
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

We are creating the object of the Message which will be passed to the object of GraphServiceClient object which will be used to call the SendMail

            var message = new Message
{
Subject = "Your subject here",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Email Content"
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "my email id"
}
}
},
CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "2nd email id"
}
}
}
};

Function 1

IConfidentialClientApplication confidentialClient = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}/v2.0"))
.Build();

// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
var authResult = await confidentialClient
.AcquireTokenForClient(scopes)
.ExecuteAsync().ConfigureAwait(false);

var token = authResult.AccessToken;
// Build the Microsoft Graph client. As the authentication provider, set an async lambda
// which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
// and inserts this access token in the Authorization header of each API request.
GraphServiceClient graphServiceClient =
new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
// Add the access token in the Authorization header of the API request.
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
})
);


await graphServiceClient.Users[userId]
.SendMail(message, false)
.Request()
.PostAsync();

Function 2

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();

var authResultDirect = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().ConfigureAwait(false);

//Microsoft.Graph.Auth is required for the following to work
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);


await graphClient.Users[userId]
.SendMail(message, false)
.Request()
.PostAsync();

The difference between Function 1 and Function 2 is very small. As explained in the function 2, Microsoft.Graph.Auth is required which is in preview in .Net Core. So, If you do not want to use Nuget package which is in preview then use Function 1 and it will work just fine.

Wrap-up

That is it. Most of the time is spent on getting the configuration right. Once you have done that, writing the code is easy as its just a few lines.

Thanks for reading. Share to give this post some love if you found it helpful.

Jatinder

  • Get the client ID.
  • Get the client secret.

--

--