|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using JetBrains.Annotations;
namespace Kaleida.ServiceMonitor.Model.Email
{
internal class ScriptEmailSender
{
private readonly string scriptName;
[CanBeNull]
private string smtpServer;
[CanBeNull]
private MailAddress senderEmail;
private readonly List<MailAddress> recipients;
public ScriptEmailSender(string scriptName, IEnumerable<MailAddress> recipients)
{
this.scriptName = scriptName;
this.recipients = recipients.ToList();
}
public void Configure(IConfiguration config)
{
if (string.IsNullOrWhiteSpace(config.SmtpServer))
throw new InvalidOperationException(string.Format("SmtpServer is not set in the config. Cannot send emails from script '{0}'", scriptName));
if (config.EmailSenderAddress == null)
throw new InvalidOperationException(string.Format("EmailSenderAddress is not set in the config. Cannot send emails from script '{0}'", scriptName));
Configure(config.SmtpServer, config.EmailSenderAddress);
}
public void Configure([NotNull] string smtp, [NotNull] MailAddress sender)
{
if (smtp == null) throw new ArgumentNullException("smtp");
if (sender == null) throw new ArgumentNullException("sender");
smtpServer = smtp;
senderEmail = sender;
}
public void TrySendEmail(NotificationMessage notification)
{
if (senderEmail == null || smtpServer == null)
throw new InvalidOperationException("Must first call Configure to set SmtpServer and EmailSenderAddress");
if (recipients.Any())
{
using (var client = new SmtpClient(smtpServer))
{
var message = new MailMessage
{
Subject = notification.Subject,
IsBodyHtml = true,
Body = "Must be viewed using HTML-compatible email client"
};
foreach (var recipient in recipients)
{
message.To.Add(recipient);
}
message.From = senderEmail;
var htmlView = AlternateView.CreateAlternateViewFromString(notification.BodyHtml, null, "text/html");
message.AlternateViews.Add(htmlView);
client.Send(message);
}
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Stuart Wheelwright is the Principal Architect and Software Developer at
BlackJet Software Ltd.
He has over 16 years commercial experience producing robust, maintainable, web-based solutions and bespoke systems for Microsoft platforms.
His latest project is
Shopping UK, an elegantly simple shopping list for iPhone.