using HJS.Entities.Models; using Microsoft.Extensions.Options; using Microsoft.Graph; using Microsoft.Identity.Client; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace HJS.Utility { public class EmailUtility { private readonly IConfidentialClientApplication _confidentialClientApplication; private readonly EmailSettings _emailSettings; private static AccessToken? _accessToken; static EmailUtility() { _accessToken = null!; } public EmailUtility(IConfidentialClientApplication confidentialClientApplication, IOptions emailSettings ) { _confidentialClientApplication = confidentialClientApplication; _emailSettings = emailSettings.Value; } /// /// Calls Send Email Mehtod which calls the MS Graph using an authenticated Http client /// public async Task SendMail(string recipient, string bcc, string cc, string subject, string body, string attachment, List attachmentModels = null) { var accessToken = await GetToken(); if (accessToken != null && !string.IsNullOrEmpty(accessToken.Token)) { Message message = new Message { Subject = subject, Body = new ItemBody { ContentType = BodyType.Html, Content = body } }; List toRecipients = new List(); List ccRecipients = new List(); List bccRecipients = new List(); // Set the recipient address of the mail message if (!string.IsNullOrEmpty(recipient)) { string[] strRecipient = recipient.Replace(";", ",").TrimEnd(',').Split(new char[] { ',' }); // Set the Bcc address of the mail message for (int intCount = 0; intCount < strRecipient.Length; intCount++) { var emailRecipient = AddEmailAddress(recipient); toRecipients.Add(emailRecipient); } } // Check if the bcc value is nothing or an empty string if (!string.IsNullOrEmpty(bcc)) { string[] strBCC = bcc.Split(new char[] { ',' }); // Set the Bcc address of the mail message for (int intCount = 0; intCount < strBCC.Length; intCount++) { var emailRecipient = AddEmailAddress(strBCC[intCount]); bccRecipients.Add(emailRecipient); } } // Check if the cc value is nothing or an empty value if (!string.IsNullOrEmpty(cc)) { // Set the CC address of the mail message string[] strCC = cc.Split(new char[] { ',' }); for (int intCount = 0; intCount < strCC.Length; intCount++) { var emailRecipient = AddEmailAddress(strCC[intCount]); ccRecipients.Add(emailRecipient); } } #region --> attachment if (attachmentModels != null && attachmentModels.Count > 0) { MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage(); foreach (var item in attachmentModels) { attachments.Add(new FileAttachment { ODataType = "#microsoft.graph.fileAttachment", ContentBytes = item.ContentBytes, ContentType = item.ContentType, ContentId = "testing", Name = item.AttachmentName }); } message.Attachments = attachments; } #endregion message.ToRecipients = toRecipients; message.CcRecipients = ccRecipients; message.BccRecipients = bccRecipients; //Create GraphServiceClient and add the access token in request header. 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", accessToken.Token); }) ); //Call the SendMail API of graph service client await graphServiceClient.Users[_emailSettings.FromEmail] .SendMail(message, false) .Request() .PostAsync(); return true; } else { return false; } } public Recipient AddEmailAddress(string address) { Recipient recipient = new Recipient(); EmailAddress emailAddress = new EmailAddress(); emailAddress.Address = address; recipient.EmailAddress = emailAddress; return recipient; } public async Task GetToken() { if (_accessToken is { Expired: false }) { return _accessToken; } _accessToken = await FetchToken(); return _accessToken; } private async Task FetchToken() { string[] scopes = new string[] { $"{_emailSettings.ApiUrl}.default" }; AuthenticationResult result = await _confidentialClientApplication.AcquireTokenForClient(scopes) .ExecuteAsync().ConfigureAwait(false); AccessToken accessToken = new AccessToken(result.AccessToken,result.ExpiresOn.DateTime); return accessToken; } } }