M365: Microsoft Graph – Part 11 – Send Email using Graph API from .Net Core Application with attachments

.Net Core application to send email using Graph API
.Net Core application to send email using Graph API

Hi All,

LIFE IS BEAUTIFUL 🙂 I hope we all are safe:) STAY SAFE, STAY HEALTHY 🙂 STAY HOME 🙂

Today again with my favorite feature “Microsoft Graph”. This is sequel of my previous Graph Article – M365: Microsoft Graph – Part 10 – Send Email using Graph API from Console Application (Background Job) 🙂

On this article one of friend asked for sending attachment as well. So thought why not to write an article 🙂

So in this article I wont get in detailed steps as already mentioned in article but will have only new changes.

In last article I have used Console Application with .Net Standard Framework, this time tried with .Net Core Framework as

M365 - Graph APIs - .Net Core Console Application
Fig1: M365 – Graph APIs – .Net Core Console Application

Please refer last article for M365: Microsoft Graph – Part 10 – Send Email using Graph API from Console Application (Background Job) for following points

Since this is .Net Core application, I am storing Azure App Key and Secret in JSON file – appsettings.json file as

M365 - Graph APIs - .Net Core Console Application - Storing details in JSON file
Fig2: M365 – Graph APIs – .Net Core Console Application – Storing details in JSON file

Following references required

M365 - Graph APIs - .Net Core Console Application - Sending Email using Graph APIs - References required
Fig3: M365 – Graph APIs – .Net Core Console Application – Sending Email using Graph APIs – References required

Following is the code to read JSON file from .NET CORE

        var config = new ConfigurationBuilder()
                 .AddJsonFile("appsettings.json")
                 .Build();
          var tenantID = config["TenantID"];
          var clientId = config["ClientId"];
          var clientSecret = config["ClientSecret"];

Now how to send attachments: There is a class calledMessageAttachmentsCollectionPage used to add multiple FileAttachment attachments as

      byte[] contentBytes = System.IO.File.ReadAllBytes(@"C:\outFile.csv");
      string contentType = "csv";
               MessageAttachmentsCollectionPage attachments = new                                
                      MessageAttachmentsCollectionPage();
                attachments.Add(new FileAttachment
                {
                    ODataType = "#microsoft.graph.fileAttachment",
                    ContentBytes = contentBytes,
                    ContentType = contentType,
                    ContentId = "testing",
                    Name = "outFile.csv"
                });

Then we have two properties for Message object –

  • HasAttachments : boolean property which indicates whether message has attachments or not
  • Attachments : collection of Attachments which we need to send. Instance of MessageAttachmentsCollectionPage class

Following is the sample of complete Message object

               var message = new Microsoft.Graph.Message
                {
                    Subject = Subject,
                    Body = new ItemBody
                    {
                        ContentType = Microsoft.Graph.BodyType.Html,
                        Content = Body
                    },
                    ToRecipients = new List<Recipient > ()
                    {
                    new Recipient
                    {

                        EmailAddress = new Microsoft.Graph.EmailAddress
                        {
                            Address = To
                        }
                    }
                    },
                    HasAttachments = true,
                    Attachments = attachments
                };

Following is the complete code

using Microsoft.Graph;
using System;
using System.Collections.Generic;

namespace MSGraphDemos
{
  public static class GraphServices
  {
  public static async void SendEmail(string To, string Subject, string Body)
  {
     try
     {
//AzureAuthProvider is our custom class. Please have a look at below code //snippet.
  AzureAuthProvider authProvider = new AzureAuthProvider();  
  GraphServiceClient _graphClient = new GraphServiceClient(authProvider);

  byte[] contentBytes = System.IO.File.ReadAllBytes(@"C:\outFile.csv");
  string contentType = "csv";

MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();
attachments.Add(new FileAttachment
{
                    ODataType = "#microsoft.graph.fileAttachment",
                    ContentBytes = contentBytes,
                    ContentType = contentType,
                    ContentId = "testing",
                    Name = "outFile.csv"
                });

                var message = new Microsoft.Graph.Message
                {
                    Subject = Subject,
                    Body = new ItemBody
                    {
                        ContentType = Microsoft.Graph.BodyType.Html,
                        Content = Body
                    },
                    ToRecipients = new List<Recipient > ()
                    {
                    new Recipient
                    {

                        EmailAddress = new Microsoft.Graph.EmailAddress
                        {
                            Address = To
                        }
                    }
                    },
                    HasAttachments = true,
                    Attachments = attachments
                };

            _graphClient.Users["prasham@knowledgejunction1.onmicrosoft.com"]
                    .SendMail(message, true)
                    .Request()
                    .PostAsync().Wait(8000);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Message " + ex.Message);
                Console.WriteLine("\nStackTrace " + ex.StackTrace);
            }
        }//SendEmail
    }//cs
}//ns

AzureAuthProvider class code:

using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace MSGraphDemos
{
 class AzureAuthProvider : IAuthenticationProvider 
    {
     public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            try
            {

                var config = new ConfigurationBuilder()
                 .AddJsonFile("appsettings.json")
                 .Build();
                var tenantID = config["TenantID"];
                var clientId = config["ClientId"];
                var clientSecret = config["ClientSecret"];

                string resource = "https://graph.microsoft.com";
                //reading tenant id from JSON file
                string authority = "https://login.windows.net/" + tenantID;

  AuthenticationContext auth = new AuthenticationContext(authority, false);
 
ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);

 var authResult = auth.AcquireTokenAsync(resource, clientCredential).Result;

                var accessToken = authResult.AccessToken;
            request.Headers.Add("Authorization", "Bearer " + accessToken);
   }
            catch (Exception ex)
            {
                //ToDo : Proper exception handling
                Console.Write("Exception Message: " + ex.Message);
                Console.Write("\n\nStack Trace: " + ex.StackTrace);
            }
        }
    }//cs
}//ns

We have very good series of articles on “Microsoft Graph” and will be coming a lot. Please visit – https://knowledge-junction.in/?s=Microsoft+graph

For any query related to Microsoft Graph feel free to ping me 🙂

Thanks for reading 🙂 If its worth at least reading once, kindly please like and share. SHARING IS CARING 🙂

Prasham Sabadra

LIFE IS VERY BEAUTIFUL :) ENJOY THE WHOLE JOURNEY :) Founder of Knowledge Junction and live-beautiful-life.com, Author, Learner, Passionate Techie, avid reader. Certified Professional Workshop Facilitator / Public Speaker. Scrum Foundation Professional certificated. Motivational, Behavioral , Technical speaker. Speaks in various events including SharePoint Saturdays, Boot camps, Collages / Schools, local chapter. Can reach me for Microsoft 365, Azure, DevOps, SharePoint, Teams, Power Platform, JavaScript.

You may also like...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: