using System; using System.Configuration; using System.IO; using System.Linq; using System.Net.Mail; using LeafWeb.Core.DAL; using LeafWeb.Core.Entities; using NLog; namespace LeafWeb.Web.Services { public class EmailNotificationService : IDisposable { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private readonly string _emaialFromAddress; private readonly SmtpClient _smtpClient; private readonly DataService _dataService; public EmailNotificationService(DataService dataService) { _dataService = dataService; _smtpClient = new SmtpClient(); _emaialFromAddress = ConfigurationManager.AppSettings["EmailFromAddress"]; } public EmailNotificationService() : this(new DataService()) { } public void SendLeafWebError(int leafInputId, string errorMessage) { var leafInput = _dataService.GetLeafInput(leafInputId); var body = $"Your leaf analysis job, {leafInput.Identifier}, encountered the following errors." + Environment.NewLine + "You will need to correct your input and resubmit." + Environment.NewLine + Environment.NewLine + errorMessage; var message = new MailMessage(_emaialFromAddress, leafInput.Email, "LeafWeb processing error", body); SendMessage(message); } public void SendLeafWebComplete(int leafInputId) { var leafInput = _dataService.GetLeafInput(leafInputId); var body = $"Your leaf analysis job, {leafInput.Identifier}, has completed." + Environment.NewLine; var message = new MailMessage(_emaialFromAddress, leafInput.Email, "LeafWeb results", body); var fileStreams = (from outputFile in leafInput.OutputFiles select Tuple.Create(outputFile, new MemoryStream(outputFile.Contents))).ToList(); try { foreach (var fileStream in fileStreams) { var attachment = new Attachment(fileStream.Item2, fileStream.Item1.Filename); message.Attachments.Add(attachment); } SendMessage(message); } finally { // can't dispose those memory streams until the message is sent foreach (var stream in fileStreams.Select(f => f.Item2)) { stream.Dispose(); } } } private void SendMessage(MailMessage mailMessage) { try { Logger.Debug("Email sending to " + mailMessage.To + ", subject: " + mailMessage.Subject); _smtpClient.Send(mailMessage); } catch (SmtpException ex) { Logger.Error(ex, "Failed to send mail: {0}", ex.Message); } } public void Dispose() { _dataService.Dispose(); } } }