Initial support for Graph API E-Mail handler
This commit is contained in:
78
TwilioSMSReceiver.Common/MessageHandlers/GraphSmtpHandler.cs
Normal file
78
TwilioSMSReceiver.Common/MessageHandlers/GraphSmtpHandler.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user