Friday, September 20, 2024

Send email using graph api if multi-factor authentication is enable using Function Account

 

If you are new to Graph API and want to send an email, then you are in the right place. If your account has multi-factor authentication disabled, just like a noreply account, let’s not waste any time and start coding. Please note, I am using Graph API version 5.56. So, let’s go! 

1st create interface

public interface IGraphMailService

{

 Task SendMailAsync(string fromAddress,string toAddress, string subject, string content, string ccEmail);

}

Service code 

using Azure.Identity;

using Dow.Mjeapi.Biz.Interfaces;

using Dow.Mjeapi.Data.Models;

using Microsoft.Extensions.Configuration;

using Microsoft.Graph;

using Microsoft.Graph.Me.SendMail;

using Microsoft.Graph.Models;

using Microsoft.Identity.Client;

using System;

using System.Collections.Generic;

using System.Threading.Tasks;

using static System.Formats.Asn1.AsnWriter;

namespace 

{

    public class GraphMailService : IGraphMailService

    {

        private readonly IConfiguration _config;

        private const string TenantId = "TenantId ";

        private const string ClientId = "ClientId "; 

        private static string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

        private const string ClientSecret = "YOURClientSecret ";

        public GraphMailService(IConfiguration config)

        {

            _config = config;

        }

        private static IPublicClientApplication CreatePublicClientApplication()

        {

            return PublicClientApplicationBuilder.Create(ClientId)

                .WithAuthority(AzureCloudInstance.AzurePublic, TenantId)

                .WithDefaultRedirectUri()

                .Build();

        }

        public async Task SendMailAsync( string fromAddress,string toAddress, string subject, string content, string ccEmail)

    {

        try

        {

            string? tenantId = _config[TenantId];

            string? clientId = _config[ClientId];

            string? userName =  _config[UserName];

            string? password = _config[Password];


            var scopes = new[] { "https://graph.microsoft.com/.default" };


            var usernamePasswordCredential = new UsernamePasswordCredential(userName, password, tenantId, clientId);


            var graphClient = new GraphServiceClient(usernamePasswordCredential, scopes);


            var message = new Message

            {

                Subject = subject,

                Body = new ItemBody

                {

                    ContentType = BodyType.Text,

                    Content = content

                },

                ToRecipients = new List<Recipient>

                {

                    new Recipient

                    {

                        EmailAddress = new EmailAddress

                        {

                            Address = toAddress

                        }

                    }

                },

                CcRecipients = new List<Recipient>

                {

                    new Recipient

                    {

                        EmailAddress = new EmailAddress

                        {

                            Address = ccEmail

                        }

                    }

                }

                //,

                //BccRecipients = new List<Recipient>

                //{

                //    new Recipient

                //    {

                //        EmailAddress = new EmailAddress

                //        {

                //            Address = bccEmail

                //        }

                //    }

                //}

            };


            var sendMailRequestBody = new Microsoft.Graph.Me.SendMail.SendMailPostRequestBody

            {

                Message = message,

                SaveToSentItems = true

            };


            await graphClient.Me.SendMail.PostAsync(sendMailRequestBody);


            

            Console.WriteLine("Email sent successfully");

        }

        catch (Exception ex)

        {

            Console.WriteLine($"An error occurred: {ex.Message}");

        }

    }

and Controller code 

using Microsoft.AspNetCore.Mvc;

using System.Threading.Tasks;

using System;

using Microsoft.AspNetCore.Authorization;


namespace ANCD.Test.Controllers

{

    [ApiController]

    [Route("api/[controller]")]

    [Authorize]

    public class EmailController : ControllerBase

    {

        private readonly IGraphMailService _graphMailService;


        public EmailController(IGraphMailService graphMailService)

        {

            _graphMailService = graphMailService;

        }

        [HttpPost("send")]

        public async Task<IActionResult> SendMail([FromBody] MailRequestNew mailRequest)

        {

            if (mailRequest == null || string.IsNullOrEmpty(mailRequest.FromAddress) || string.IsNullOrEmpty(mailRequest.ToAddress) || string.IsNullOrEmpty(mailRequest.Subject) || string.IsNullOrEmpty(mailRequest.Content))

            {

                return BadRequest("Invalid mail request.");

            }


            try

            {

                await _graphMailService.SendMailAsync(mailRequest.FromAddress, mailRequest.ToAddress, mailRequest.Subject, mailRequest.Content, mailRequest.CcEmail);

                return Ok("Mail sent successfully.");

            }

            catch (Exception ex)

            {

                return StatusCode(500, $"Internal server error: {ex.Message}");

            }

        }


    }


    public class MailRequestNew

    {

        public string FromAddress { get; set; }

        public string ToAddress { get; set; }

        public string Subject { get; set; }

        public string Content { get; set; }

        public string CcEmail { get; set; }

    }


}

 adjust the azure permission  if your are issue to send email these code is tested from my end  Thank you.

Happy codding


No comments:

Post a Comment