You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

226 lines
8.5 KiB

using Common.Models.Confiq;
using Common.Models.Enums;
using Common.Models.Notification;
using Common.Models.RequestResponse;
using Common.Utility;
using log4net;
using Newtonsoft.Json;
using Repository.DAO.ThirdParty;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
namespace Business.BusinessLogic.NotificationApiService
{
public class EmailService
{
private readonly ILog _log = LogManager.GetLogger(typeof(EmailService));
private readonly IThirdPartyRepo _thirdPartyRepo;
public EmailService()
{
_thirdPartyRepo = new ThirdPartyRepo();
}
public TPResponse SendEmail(SendNotificationRequest model)
{
TPResponse _tPResponse = new TPResponse();
// _log.Info($"IsBulkNotification {model.IsBulkNotification}");
List<TPResponse> tPResponses = new List<TPResponse>();
Task.Run(() =>
{
model.Recipients.ForEach(x =>
{
tPResponses.Add(Email(x, model.Template));
});
}).ContinueWith(y =>
{
_log.Debug($"SendEmail Responses {JsonConvert.SerializeObject(tPResponses)}");
_tPResponse.Data = tPResponses;
//tPResponses.Where(x => x.ResponseCode.Equals("0")).ToList().ForEach(z =>
//{
// _thirdPartyRepo.UpdateNotificationStatus(z.Id);
//});
});
_tPResponse.ResponseCode = "0";
_tPResponse.Msg = "Email sent succesfully. Check log for details.";
return _tPResponse;
}
private TPResponse Email(RecipientViewModel model, NotifyTemplate template = NotifyTemplate.NONE)
{
TPResponse _tPResponse = new TPResponse() { ResponseCode = "1", Id = model.Address };
SmtpClient SmtpServer = new SmtpClient();
MailMessage mail = new MailMessage();
_log.Info($"Sending email for {model.Address}");
try
{
if (model.MailAddress != null && !string.IsNullOrEmpty(model.MailAddress.FromEmail))
{
mail.From = new MailAddress(model.MailAddress.FromEmail, model.MailAddress.AliasName ?? string.Empty);
}
if (!string.IsNullOrEmpty(model.Address))
{
mail.To.Add(model.Address);
}
if (!string.IsNullOrEmpty(model.CcAddress))
{
mail.To.Add(model.CcAddress);
}
if (!string.IsNullOrEmpty(model.BccAddress))
{
mail.To.Add(model.BccAddress);
}
if (model.NotificationContent.Attachments != null)
{
foreach (var item in model.NotificationContent.Attachments)
{
Attachment attachment = null;
if (!string.IsNullOrEmpty(item.FilePath))
{
attachment = new Attachment(item.FilePath, item.FileType);
}
else
{
var bytes = Convert.FromBase64String(item.Byte64String);
MemoryStream strm = new MemoryStream(bytes);
attachment = new Attachment(strm, item.FileName);
}
if (attachment != null)
{
ContentDisposition disposition = attachment.ContentDisposition;
disposition.Inline = true;
disposition.FileName = Path.GetFileName(item.FileName);
disposition.DispositionType = DispositionTypeNames.Attachment;
mail.Attachments.Add(attachment);
}
}
}
if (model.NotificationContent.EmbeddedResources != null)
{
if (model.NotificationContent.EmbeddedResources.Any())
{
AlternateView vw = GetEmbeddedImage(model.NotificationContent.EmbeddedResources, model.NotificationContent.Body);
mail.AlternateViews.Add(vw);
}
}
mail.Subject = model.NotificationContent.Title;
mail.IsBodyHtml = true;
if (template != NotifyTemplate.NONE)
{
var templatePath = Helpers.GetMapping(Common.Models.Enums.MappingType.EMAIL_TEMPLATE, template.ToString());
string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, templatePath.DValue);
mail.Subject = templatePath.DText;
string body = string.Empty;
using (StreamReader reader = new StreamReader(fullPath))
{
body = reader.ReadToEnd();
}
if (!string.IsNullOrEmpty(model.NotificationContent.Body) && !model.NotificationContent.Body.StartsWith("<img"))
{
List<Mapping> mappings = JsonConvert.DeserializeObject<List<Mapping>>(model.NotificationContent.Body);
mappings.ForEach(x =>
{
body = body.Replace(string.Format("{{{0}}}", x.SValue), x.SText);
});
}
mail.Body = body;
}
else
mail.Body = model.NotificationContent.Body;
// SmtpServer.Timeout = 25000;
SmtpServer.Send(mail);
mail.Dispose();
SmtpServer.Dispose();
_tPResponse.ResponseCode = "0";
_tPResponse.Id = model.BroadCastNoticeId.ToString();
_tPResponse.Msg = _tPResponse.ResponseCode.Equals("0") ? "Email Sent Sucessfully." : "Email Sending Failed.";
_thirdPartyRepo.UpdateNotificationStatus(model.BroadCastNoticeId.ToString());
_log.Info($"Sending email for {model.Address} | {JsonConvert.SerializeObject(_tPResponse)}");
}
catch (SmtpFailedRecipientsException ex)
{
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
{
// Console.WriteLine("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
SmtpServer.Send(mail);
}
else
{
// Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient);
//throw ex;
_tPResponse.Msg = ex.Message;
_log.Error($"Error Sending email for {model.Address}", ex);
}
}
_tPResponse.ResponseCode = "1";
}
catch (Exception ex)
{
_tPResponse.ResponseCode = "1";
_tPResponse.Msg = ex.Message;
_log.Error($"Error Sending email for {model.Address}", ex);
}
finally
{
// SmtpServer.Dispose();
}
return _tPResponse;
}
private AlternateView GetEmbeddedImage(List<AttachmentModel> attachmentList, string htmlBody)
{
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
foreach (var item in attachmentList)
{
byte[] bytes = System.Convert.FromBase64String(item.Byte64String);
LinkedResource res = new LinkedResource(new MemoryStream(bytes), item.FileType);
res.ContentId = item.FileName;
alternateView.LinkedResources.Add(res);
}
return alternateView;
}
}
}