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

  1. using Common.Models.Confiq;
  2. using Common.Models.Enums;
  3. using Common.Models.Notification;
  4. using Common.Models.RequestResponse;
  5. using Common.Utility;
  6. using log4net;
  7. using Newtonsoft.Json;
  8. using Repository.DAO.ThirdParty;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net.Mail;
  14. using System.Net.Mime;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. namespace Business.BusinessLogic.NotificationApiService
  18. {
  19. public class EmailService
  20. {
  21. private readonly ILog _log = LogManager.GetLogger(typeof(EmailService));
  22. private readonly IThirdPartyRepo _thirdPartyRepo;
  23. public EmailService()
  24. {
  25. _thirdPartyRepo = new ThirdPartyRepo();
  26. }
  27. public TPResponse SendEmail(SendNotificationRequest model)
  28. {
  29. TPResponse _tPResponse = new TPResponse();
  30. // _log.Info($"IsBulkNotification {model.IsBulkNotification}");
  31. List<TPResponse> tPResponses = new List<TPResponse>();
  32. Task.Run(() =>
  33. {
  34. model.Recipients.ForEach(x =>
  35. {
  36. tPResponses.Add(Email(x, model.Template));
  37. });
  38. }).ContinueWith(y =>
  39. {
  40. _log.Debug($"SendEmail Responses {JsonConvert.SerializeObject(tPResponses)}");
  41. _tPResponse.Data = tPResponses;
  42. //tPResponses.Where(x => x.ResponseCode.Equals("0")).ToList().ForEach(z =>
  43. //{
  44. // _thirdPartyRepo.UpdateNotificationStatus(z.Id);
  45. //});
  46. });
  47. _tPResponse.ResponseCode = "0";
  48. _tPResponse.Msg = "Email sent succesfully. Check log for details.";
  49. return _tPResponse;
  50. }
  51. private TPResponse Email(RecipientViewModel model, NotifyTemplate template = NotifyTemplate.NONE)
  52. {
  53. TPResponse _tPResponse = new TPResponse() { ResponseCode = "1", Id = model.Address };
  54. SmtpClient SmtpServer = new SmtpClient();
  55. MailMessage mail = new MailMessage();
  56. _log.Info($"Sending email for {model.Address}");
  57. try
  58. {
  59. if (model.MailAddress != null && !string.IsNullOrEmpty(model.MailAddress.FromEmail))
  60. {
  61. mail.From = new MailAddress(model.MailAddress.FromEmail, model.MailAddress.AliasName ?? string.Empty);
  62. }
  63. if (!string.IsNullOrEmpty(model.Address))
  64. {
  65. mail.To.Add(model.Address);
  66. }
  67. if (!string.IsNullOrEmpty(model.CcAddress))
  68. {
  69. mail.To.Add(model.CcAddress);
  70. }
  71. if (!string.IsNullOrEmpty(model.BccAddress))
  72. {
  73. mail.To.Add(model.BccAddress);
  74. }
  75. if (model.NotificationContent.Attachments != null)
  76. {
  77. foreach (var item in model.NotificationContent.Attachments)
  78. {
  79. Attachment attachment = null;
  80. if (!string.IsNullOrEmpty(item.FilePath))
  81. {
  82. attachment = new Attachment(item.FilePath, item.FileType);
  83. }
  84. else
  85. {
  86. var bytes = Convert.FromBase64String(item.Byte64String);
  87. MemoryStream strm = new MemoryStream(bytes);
  88. attachment = new Attachment(strm, item.FileName);
  89. }
  90. if (attachment != null)
  91. {
  92. ContentDisposition disposition = attachment.ContentDisposition;
  93. disposition.Inline = true;
  94. disposition.FileName = Path.GetFileName(item.FileName);
  95. disposition.DispositionType = DispositionTypeNames.Attachment;
  96. mail.Attachments.Add(attachment);
  97. }
  98. }
  99. }
  100. if (model.NotificationContent.EmbeddedResources != null)
  101. {
  102. if (model.NotificationContent.EmbeddedResources.Any())
  103. {
  104. AlternateView vw = GetEmbeddedImage(model.NotificationContent.EmbeddedResources, model.NotificationContent.Body);
  105. mail.AlternateViews.Add(vw);
  106. }
  107. }
  108. mail.Subject = model.NotificationContent.Title;
  109. mail.IsBodyHtml = true;
  110. if (template != NotifyTemplate.NONE)
  111. {
  112. var templatePath = Helpers.GetMapping(Common.Models.Enums.MappingType.EMAIL_TEMPLATE, template.ToString());
  113. string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, templatePath.DValue);
  114. mail.Subject = templatePath.DText;
  115. string body = string.Empty;
  116. using (StreamReader reader = new StreamReader(fullPath))
  117. {
  118. body = reader.ReadToEnd();
  119. }
  120. if (!string.IsNullOrEmpty(model.NotificationContent.Body) && !model.NotificationContent.Body.StartsWith("<img"))
  121. {
  122. List<Mapping> mappings = JsonConvert.DeserializeObject<List<Mapping>>(model.NotificationContent.Body);
  123. mappings.ForEach(x =>
  124. {
  125. body = body.Replace(string.Format("{{{0}}}", x.SValue), x.SText);
  126. });
  127. }
  128. mail.Body = body;
  129. }
  130. else
  131. mail.Body = model.NotificationContent.Body;
  132. // SmtpServer.Timeout = 25000;
  133. SmtpServer.Send(mail);
  134. mail.Dispose();
  135. SmtpServer.Dispose();
  136. _tPResponse.ResponseCode = "0";
  137. _tPResponse.Id = model.BroadCastNoticeId.ToString();
  138. _tPResponse.Msg = _tPResponse.ResponseCode.Equals("0") ? "Email Sent Sucessfully." : "Email Sending Failed.";
  139. _thirdPartyRepo.UpdateNotificationStatus(model.BroadCastNoticeId.ToString());
  140. _log.Info($"Sending email for {model.Address} | {JsonConvert.SerializeObject(_tPResponse)}");
  141. }
  142. catch (SmtpFailedRecipientsException ex)
  143. {
  144. for (int i = 0; i < ex.InnerExceptions.Length; i++)
  145. {
  146. SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
  147. if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
  148. {
  149. // Console.WriteLine("Delivery failed - retrying in 5 seconds.");
  150. System.Threading.Thread.Sleep(5000);
  151. SmtpServer.Send(mail);
  152. }
  153. else
  154. {
  155. // Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient);
  156. //throw ex;
  157. _tPResponse.Msg = ex.Message;
  158. _log.Error($"Error Sending email for {model.Address}", ex);
  159. }
  160. }
  161. _tPResponse.ResponseCode = "1";
  162. }
  163. catch (Exception ex)
  164. {
  165. _tPResponse.ResponseCode = "1";
  166. _tPResponse.Msg = ex.Message;
  167. _log.Error($"Error Sending email for {model.Address}", ex);
  168. }
  169. finally
  170. {
  171. // SmtpServer.Dispose();
  172. }
  173. return _tPResponse;
  174. }
  175. private AlternateView GetEmbeddedImage(List<AttachmentModel> attachmentList, string htmlBody)
  176. {
  177. AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
  178. foreach (var item in attachmentList)
  179. {
  180. byte[] bytes = System.Convert.FromBase64String(item.Byte64String);
  181. LinkedResource res = new LinkedResource(new MemoryStream(bytes), item.FileType);
  182. res.ContentId = item.FileName;
  183. alternateView.LinkedResources.Add(res);
  184. }
  185. return alternateView;
  186. }
  187. }
  188. }