Files
LeafWeb/Web/Services/EmailNotificationService.cs
T

93 lines
2.6 KiB
C#

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 leafWebFileId, string errorMessage)
{
var file = _dataService.GetLeafInputFile(leafWebFileId);
var body = $"Your LeafWeb analysis job, {file.LeafInput.Identifier} (with filename {file.Filename}), 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, file.LeafInput.Email, "LeafWeb processing error", body);
SendMessage(message);
}
public void SendLeafWebSuccess(int leafWebFileId)
{
var file = _dataService.GetLeafInputFile(leafWebFileId);
var body = $"Your LeafWeb analysis job, {file.LeafInput.Identifier} (with filename {file.Filename}), has completed." + Environment.NewLine;
var message = new MailMessage(_emaialFromAddress, file.LeafInput.Email, "LeafWeb results", body);
var fileStreams =
(from outputFile in
file.LeafOutputFiles
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();
}
}
}