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 readonly IMailNotificationOptions _mailNotificationOptions;
#endregion
#region Fields
// The SMTP client to send the mail notification messages
private readonly SmtpClient _smtpClient;
#endregion
#region Ctor
///
/// Initializes a new instance of the MailNotificationService class
///
/// The dependant mail notification options.
public MailNotificationService(
IMailNotificationOptions mailNotificationOptions)
{
_mailNotificationOptions = mailNotificationOptions;
// 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
}
}