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 SendEmailAsync(Message mail);
}
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 SendEmailAsync(Message mail)
{
var clientSecretCredential = new ClientSecretCredential(TenantId, ClientId, ClientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var sendMailBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody
{
Message = mail,
SaveToSentItems = true
};
try
{
await graphClient.Users["mjesupport@dow.com"].SendMail.PostAsync(sendMailBody);
}
catch (Exception e)
{
Console.WriteLine($"Error sending email: {e.Message}");
}
}
}
}
and Controller code
[HttpPost("send")]
public async Task<IActionResult> SendEmail(string recipientEmail, string subject, string body)
{
var message = CreateEmailMessage(recipientEmail, subject, body);
await _graphMailService.SendEmailAsync(message);
return Ok("Email sent successfully");
}
private Message CreateEmailMessage(string recipientEmail, string subject, string body)
{
return new Message
{
Subject = subject,
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = body
},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = recipientEmail
}
}
}
};
} 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