Initial support for Graph API E-Mail handler

This commit is contained in:
2023-01-24 15:43:42 -08:00
parent 4c07a777c3
commit 587c21fa03
4 changed files with 88 additions and 6 deletions

View File

@@ -0,0 +1,78 @@
using System;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using TwilioSMSReceiver.Common.Interfaces;
using TwilioSMSReceiver.Data.Models;
namespace TwilioSMSReceiver.Common.MessageHandlers
{
public class GraphSmtpHandler : IMessageHandler
{
protected readonly ILogger _logger;
protected readonly IConfiguration _configuration;
protected GraphServiceClient BuildGraphClient()
{
var section = _configuration.GetSection("GraphSmtp");
var tenantId = section["tenantId"];
var appId = section["appId"];
var secret = section["secret"];
var scopes = new[] { "https://graph.microsoft.com/.default" };
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(
tenantId, appId, secret, options);
return new GraphServiceClient(clientSecretCredential, scopes);
}
public GraphSmtpHandler(ILogger logger, IConfiguration configuration)
{
_configuration = configuration;
_logger = logger;
}
public async Task<bool> RelaySms(SMSModel model)
{
var message = new Message
{
Subject = $"Received SMS from {model.SenderNumber} to {model.SenderNumber}",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = model.MessageContents
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "frannis@contoso.onmicrosoft.com"
}
}
}
};
try
{
var graphClient = BuildGraphClient();
await graphClient.Me.SendMail(message).Request().PostAsync();
return true;
}
catch (Exception e)
{
_logger.LogWarning($"Error occured {e}");
}
return false;
}
}
}