using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace GreenTree.Strohrmann.ERP.Services.Notification { public class MailNotificationService : INotificationService { #region DI fields // The global mail notification options object private MailNotificationOptions _mailNotificationOptions; #endregion #region Fields // The SMTP client to send the mail notification messages private SmtpClient _smtpClient; #endregion #region Ctor /// /// Initializes a new instance of the MailNotificationService class /// /// The dependant mail notification options. public MailNotificationService( IOptionsMonitor mailNotificationOptions) { ConfigureService(mailNotificationOptions.CurrentValue); mailNotificationOptions.OnChange(config => { ConfigureService(mailNotificationOptions.CurrentValue); }); } #endregion #region Configuration /// /// Configure current service /// /// The service options. private void ConfigureService(MailNotificationOptions options) { _mailNotificationOptions = options; // Create private SMTP client based to mail notification options _smtpClient = new SmtpClient(_mailNotificationOptions.SmtpServerAddress); // Check if Username is configured if (String.IsNullOrEmpty(_mailNotificationOptions.SmtpServerUsername)) return; // Use credentials on SMTP client _smtpClient.Credentials = new NetworkCredential(_mailNotificationOptions.SmtpServerUsername, _mailNotificationOptions.SmtpServerPassword, _mailNotificationOptions.SmtpServerDomain); } #endregion #region Implementation /// /// Sends a notification to a specific target /// /// The single target. /// The subject. /// The message. public void SendNotification(string target, string subject, string message) { // Parameter validation check if (String.IsNullOrEmpty(target)) throw new ArgumentException("Cannot send notification to empty target.", "target"); // Send message via SMTP client _smtpClient.Send(new MailMessage(_mailNotificationOptions.From, target, subject, message)); } /// /// Sends a notification to multiple targets /// /// The targets. /// The subject. /// The message. public void SendNotification(string[] targets, string subject, string message) { // Paramter validation check if (targets == null) throw new ArgumentException("Cannot send notification to empty targets.", "targets"); // Loop through targets foreach (var target in targets) { // Use single SendNotification method for multiple targets SendNotification(target, subject, message); } } #endregion } }