-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
mtokarev
committed
May 15, 2024
1 parent
8664f78
commit 8ca0c44
Showing
6 changed files
with
264 additions
and
180 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
using System; | ||
using SendGrid; | ||
using SendGrid.Helpers.Mail; | ||
using System.Collections.Generic; | ||
using System.Net; | ||
using System.Threading.Tasks; | ||
using Serilog.Core; | ||
using Microsoft.Extensions.Configuration; | ||
using System.IO; | ||
using System.Net.Mail; | ||
|
||
namespace mailSender | ||
{ | ||
public class MailService | ||
{ | ||
private readonly IConfiguration _config; | ||
private readonly Logger _logger; | ||
private readonly EmailAddress _mailFrom; | ||
private readonly bool _isSimulationModeEnabled; | ||
private readonly string _mailSubject, | ||
_ccRecipient; | ||
|
||
public MailService(IConfiguration config, Logger logger) | ||
{ | ||
ValidateAndAssignConfig(config); | ||
|
||
_config = config; | ||
_logger = logger; | ||
|
||
_mailFrom = new EmailAddress(_config.GetSection("SendGrid:SenderEmail").Value, | ||
_config.GetSection("SendGrid:SenderName").Value); | ||
_isSimulationModeEnabled = bool.Parse( | ||
_config.GetSection("SendGrid:SimulationModeEnabled").Value); | ||
_mailSubject = _config.GetSection("SendGrid:MailSubject").Value; | ||
_ccRecipient = _config.GetSection("SendGrid:CcRecipient").Value; | ||
|
||
} | ||
|
||
public async Task SendBrthEmailsAsync(List<UserPrincipalExtension> sendTos) | ||
{ | ||
string mailTemplate; | ||
|
||
try | ||
{ | ||
// Read file from mail template. | ||
mailTemplate = File.ReadAllText(_config.GetSection("SendGrid:MailTemplateHtml").Value); | ||
} | ||
catch (Exception e) | ||
{ | ||
_logger.Error($"Unable to read mail template file: '{_config.GetSection("SendGrid:MailTemplateHtml").Value}'. Exception: '{e.Message}'."); | ||
|
||
return; | ||
} | ||
|
||
if (_isSimulationModeEnabled) | ||
{ | ||
_logger.Information("--- Simulation mode turned ON. No email will be sent to the users. You can turn it off in appsettings.json"); | ||
} | ||
|
||
var client = new SendGridClient(_config.GetSection("SendGrid:ApiKey").Value); | ||
|
||
foreach (var user in sendTos) | ||
{ | ||
// Replacing message subject and body with user display name. | ||
SendGridMessage mail = CreateMail( | ||
_mailFrom, | ||
_mailSubject, | ||
mailTemplate, | ||
user); | ||
|
||
// Adding user email to the 'To' field. | ||
mail.AddTo(user.EmailAddress); | ||
|
||
// If we have recipient to add to CC. | ||
if (!string.IsNullOrEmpty(_ccRecipient)) | ||
{ | ||
mail.AddCc(_ccRecipient); | ||
} | ||
|
||
// If simulation mode is enabled just log message and continue. | ||
if (_isSimulationModeEnabled) | ||
{ | ||
_logger.Information($"E-mail won't sent to '{user.EmailAddress}'."); | ||
continue; | ||
} | ||
|
||
// Adding task to the list. | ||
// Creating client and sending messages. | ||
var result = await client.SendEmailAsync(mail); | ||
|
||
// Logging results | ||
if (result.StatusCode != HttpStatusCode.Accepted) | ||
{ | ||
_logger.Error($"Unable send email to: '{user.EmailAddress}'. Status code '{result.StatusCode}'."); | ||
} | ||
else if (result.StatusCode == HttpStatusCode.Accepted) | ||
{ | ||
_logger.Information($"Mail has been sent to: '{user.EmailAddress}'."); | ||
} | ||
} | ||
} | ||
|
||
private static SendGridMessage CreateMail(EmailAddress mailFrom, | ||
string mailSubject, | ||
string mailTemplate, | ||
UserPrincipalExtension user) | ||
{ | ||
var compiledMailTemplate = mailTemplate.Replace("{{name}}", user.DisplayName); | ||
var compiledMailSubject = mailSubject.Replace("{{name}}", user.DisplayName); | ||
|
||
var mail = new SendGridMessage | ||
{ | ||
From = mailFrom, | ||
Subject = compiledMailSubject, | ||
PlainTextContent = compiledMailTemplate, | ||
HtmlContent = compiledMailTemplate | ||
}; | ||
return mail; | ||
} | ||
|
||
private void ValidateAndAssignConfig(IConfiguration config) | ||
{ | ||
string sender = _config.GetSection("SendGrid:SenderEmail").Value; | ||
if (string.IsNullOrEmpty(_config.GetSection("SendGrid:SenderName").Value) | ||
&& string.IsNullOrEmpty(sender)) | ||
{ | ||
_logger.Fatal("Please provide 'SenderEmail' and 'SenderName' in appSettings.json"); | ||
} | ||
|
||
if (!string.IsNullOrEmpty(sender) && !MailAddress.TryCreate(sender, out var _)) | ||
{ | ||
_logger.Fatal("'SenderEmail' must be a valid email address. Value provided: '{Sender}'.", | ||
sender); | ||
} | ||
|
||
if (bool.TryParse(_config.GetSection("SendGrid:SimulationModeEnabled").Value, out bool _)) | ||
{ | ||
_logger.Fatal("'SimulationModeEnabled' must to be set in appsetting.json as 'true' or 'false'."); | ||
} | ||
|
||
string ccRecipient = _config.GetSection("SendGrid:CcRecipient").Value; | ||
if (!MailAddress.TryCreate(sender, out var _) | ||
&& !string.IsNullOrEmpty(ccRecipient)) | ||
{ | ||
_logger.Fatal("'CcResipient' must be empty or have a valid email address. Value provided: '{CcRecipient}'.", | ||
ccRecipient); | ||
} | ||
|
||
throw new ArgumentException($"One or more parameter provided for '{nameof(MailService)}' are incorrect. " + | ||
"Please check the log for more information"); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.