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.

Emailer.cs 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. using System.Net.Mail;
  2. using System.Net;
  3. namespace Diligent.WebAPI.Business.Services
  4. {
  5. /// <summary>
  6. /// Provieds an API for sending emails in both sync & async fashion, as well as sending emails with delays.
  7. /// </summary>
  8. public class Emailer : IEmailer
  9. {
  10. private readonly MailSettings _settings;
  11. private readonly ILogger<Emailer> _logger;
  12. public Emailer(IOptions<MailSettings> mailSettings, ILogger<Emailer> logger)
  13. {
  14. _settings = mailSettings.Value;
  15. _logger = logger;
  16. }
  17. /// <summary>
  18. /// Sends an email asynchronously and inserts a new <see cref="DiligEmail"/> record to the underlying database.
  19. /// </summary>
  20. /// <param name="to"></param>
  21. /// <param name="subject"></param>
  22. /// <param name="body"></param>
  23. /// <param name="isHtml"></param>
  24. /// <param name="attachments"></param>
  25. /// <param name="cc"></param>
  26. /// <exception cref="ArgumentException"></exception>
  27. /// <see cref="ArgumentNullException"/>
  28. /// <exception cref="Exception"></exception>
  29. /// <returns></returns>
  30. public async Task<bool> SendEmailAndWriteToDbAsync(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null)
  31. {
  32. _logger.LogInformation($"Start sending email to {to}");
  33. var emailResult = await SendEmailAsync(to, subject, body, isHtml, cc);
  34. //_logger.LogInformation("Create email entity for save in db");
  35. var email = CreateEmail(to, subject, body, isHtml);
  36. if (emailResult)
  37. {
  38. email.SentTime = DateTime.Now;
  39. }
  40. //_logger.LogInformation("Save email in db");
  41. //var dbResult = await WriteEmailToDbAsync(email);
  42. //_logger.LogInformation("Email is saved in db.");
  43. return emailResult; // && dbResult > 0;
  44. }
  45. public async Task<bool> SendEmailAndWriteToDbAsync(string to, string subject, string body, bool isHtml = false, List<string> cc = null)
  46. {
  47. return await SendEmailAndWriteToDbAsync(new List<string> { to }, subject, body, isHtml, cc);
  48. }
  49. /// <summary>
  50. /// Sends an email synchronously and inserts a new <see cref="DiligEmail"/> record to the underlying database.
  51. /// </summary>
  52. /// <param name="to"></param>
  53. /// <param name="subject"></param>
  54. /// <param name="body"></param>
  55. /// <param name="isHtml"></param>
  56. /// <param name="attachments"></param>
  57. /// <param name="cc"></param>
  58. /// <exception cref="ArgumentException"></exception>
  59. /// <see cref="ArgumentNullException"/>
  60. /// <exception cref="Exception"></exception>
  61. /// <returns></returns>
  62. public bool SendEmailAndWriteToDb(List<string> to, string subject, string body, bool isHtml = false,
  63. List<string> cc = null)
  64. {
  65. var emailResult = SendEmail(to, subject, body, isHtml, cc);
  66. var email = CreateEmail(to, subject, body, isHtml);
  67. if (emailResult)
  68. {
  69. email.SentTime = DateTime.Now;
  70. }
  71. //var dbResult = WriteEmailToDb(email);
  72. return emailResult; // && dbResult > 0;
  73. }
  74. public bool SendEmailAndWriteToDb(string to, string subject, string body, bool isHtml = false,
  75. List<string> cc = null)
  76. {
  77. return SendEmailAndWriteToDb(new List<string> { to }, subject, body, isHtml, cc);
  78. }
  79. /// <summary>
  80. /// Sends an email synchronously.
  81. /// </summary>
  82. /// <param name="to"></param>
  83. /// <param name="subject"></param>
  84. /// <param name="body"></param>
  85. /// <param name="isHtml"></param>
  86. /// <param name="attachments"></param>
  87. /// <param name="cc"></param>
  88. /// <exception cref="ArgumentException"></exception>
  89. /// <see cref="ArgumentNullException"/>
  90. /// <exception cref="Exception"></exception>
  91. /// <returns></returns>
  92. public bool SendEmail(List<string> to, string subject, string body, bool isHtml = false,
  93. List<string> cc = null)
  94. {
  95. try
  96. {
  97. using (var smtp = GetSmtpClient())
  98. {
  99. var message = GetMailMessage(to, subject, body, isHtml, cc);
  100. smtp.Send(message);
  101. return true;
  102. }
  103. }
  104. catch (ArgumentException)
  105. {
  106. throw;
  107. }
  108. catch (Exception e)
  109. {
  110. throw new Exception("Failed to send email message.", e);
  111. }
  112. }
  113. /// <summary>
  114. /// Sends an email asynchronously.
  115. /// </summary>
  116. /// <param name="to"></param>
  117. /// <param name="subject"></param>
  118. /// <param name="body"></param>
  119. /// <param name="isHtml"></param>
  120. /// <param name="attachments"></param>
  121. /// <param name="cc"></param>
  122. /// <exception cref="ArgumentException"></exception>
  123. /// <see cref="ArgumentNullException"/>
  124. /// <exception cref="Exception"></exception>
  125. /// <returns></returns>
  126. public async Task<bool> SendEmailAsync(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null)
  127. {
  128. try
  129. {
  130. _logger.LogInformation("Getting SMTP client settings from appsettings file");
  131. using (var smtp = GetSmtpClient())
  132. {
  133. _logger.LogInformation("Create mail message");
  134. var message = GetMailMessage(to, subject, body, isHtml, cc);
  135. _logger.LogInformation("Message created.");
  136. _logger.LogInformation("Sending message to client");
  137. await smtp.SendMailAsync(message);
  138. _logger.LogInformation("Email message sent.");
  139. return true;
  140. }
  141. }
  142. catch (ArgumentException ex)
  143. {
  144. _logger.LogInformation($"Error in arguments {ex}");
  145. throw;
  146. }
  147. catch (Exception e)
  148. {
  149. _logger.LogInformation($"Error {e}");
  150. throw new Exception("Failed to send email message.", e);
  151. }
  152. }
  153. /// <summary>
  154. /// Creates a <see cref="SmtpClient"/> object and configures it.
  155. /// </summary>
  156. /// <returns></returns>
  157. public SmtpClient GetSmtpClient()
  158. {
  159. var smtp = new SmtpClient(_settings.SmtpServer) { Timeout = 1000000 };
  160. if (!string.IsNullOrWhiteSpace(_settings.SmtpUsername))
  161. {
  162. smtp.UseDefaultCredentials = false;
  163. smtp.Credentials = new NetworkCredential(
  164. _settings.SmtpUsername,
  165. _settings.SmtpPassword);
  166. smtp.EnableSsl = _settings.SmtpUseSSL;
  167. smtp.Port = _settings.SmtpPort;
  168. }
  169. return smtp;
  170. }
  171. /// <summary>
  172. /// Creates a new <see cref="MailMessage"/> from the specified arguments.
  173. /// </summary>
  174. /// <param name="to"></param>
  175. /// <param name="subject"></param>
  176. /// <param name="body"></param>
  177. /// <param name="isHtml"></param>
  178. /// <param name="attachments"></param>
  179. /// <param name="cc"></param>
  180. /// <exception cref="ArgumentException"></exception>
  181. /// <returns></returns>
  182. public MailMessage GetMailMessage(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null)
  183. {
  184. var message = new MailMessage
  185. {
  186. Sender = new MailAddress(_settings.SmtpFrom, _settings.SmtpFromName),
  187. From = new MailAddress(_settings.SmtpFrom),
  188. Subject = subject,
  189. Body = body,
  190. IsBodyHtml = isHtml
  191. };
  192. if (to.Any())
  193. {
  194. message.To.Add(string.Join(",", to.Where(email => !string.IsNullOrWhiteSpace(email))));
  195. }
  196. else
  197. {
  198. throw new ArgumentException("The list of recipient emails can not be empty");
  199. }
  200. if (cc != null && cc.Any())
  201. {
  202. message.CC.Add(string.Join(",", cc.Where(email => !string.IsNullOrWhiteSpace(email))));
  203. }
  204. return message;
  205. }
  206. /// <summary>
  207. /// Sends an email aysnchronously. If the "dont send before" argument is specified, then the email will be sent with a delay - after the specified time.
  208. /// </summary>
  209. /// <param name="to"></param>
  210. /// <param name="subject"></param>
  211. /// <param name="body"></param>
  212. /// <param name="isHtml"></param>
  213. /// <param name="attachments"></param>
  214. /// <param name="dontSendBefore"></param>
  215. /// <exception cref="ArgumentException"></exception>
  216. /// <exception cref="Exception"></exception>
  217. /// <returns></returns>
  218. //public async Task<bool> SendEmailWithDelayAsync(List<string> to, string subject, string body, bool isHtml = false, DateTime? dontSendBefore = null)
  219. //{
  220. // try
  221. // {
  222. // var email = CreateEmail(to, subject, body, isHtml, dontSendBefore);
  223. // //var result = await WriteEmailToDbAsync(email);
  224. // return true;
  225. // }
  226. // catch (ArgumentException)
  227. // {
  228. // throw;
  229. // }
  230. // catch (Exception e)
  231. // {
  232. // throw new Exception("Error while attempting to send an email with delay.", e);
  233. // }
  234. //}
  235. /// <summary>
  236. /// Creates a <see cref="DiligEmail"/> object with specified arguments.
  237. /// </summary>
  238. /// <param name="to"></param>
  239. /// <param name="subject"></param>
  240. /// <param name="body"></param>
  241. /// <param name="isHtml"></param>
  242. /// <param name="attachments"></param>
  243. /// <param name="dontSendBefore"></param>
  244. /// <exception cref="ArgumentException"></exception>
  245. /// <returns></returns>
  246. public DiligEmail CreateEmail(List<string> to, string subject, string body, bool isHtml = false,
  247. DateTime? dontSendBefore = null)
  248. {
  249. if (!to.Any())
  250. {
  251. throw new ArgumentException("The list of recipient emails can not be empty");
  252. }
  253. var email = new DiligEmail
  254. {
  255. To = to.Aggregate((previous, next) => previous + ";" + next),
  256. Subject = subject,
  257. Body = body,
  258. IsHtml = isHtml,
  259. DontSendBefore = dontSendBefore,
  260. CreateTime = DateTime.Now
  261. };
  262. return email;
  263. }
  264. /// <summary>
  265. /// Fills the specified <see cref="DiligEmail"/> object with the specified <see cref="EmailAttachment"/> list.
  266. /// </summary>
  267. /// <param name="email"></param>
  268. /// <param name="attachments"></param>
  269. /// <exception cref="ArgumentException"></exception>
  270. /// <returns></returns>
  271. //public DiligEmail FillEmailAttachments(DiligEmail email)
  272. //{
  273. // if (email == null)
  274. // {
  275. // throw new ArgumentNullException(nameof(email), "Email can not be null");
  276. // }
  277. // if (attachments != null && attachments.Any())
  278. // {
  279. // attachments.ForEach(attachment =>
  280. // {
  281. // email.DiligEmailAttachments.Add(new DiligEmailAttachment
  282. // {
  283. // FileName = attachment.FileName,
  284. // SourceFileName = attachment.SourceFileName,
  285. // Type = attachment.Type,
  286. // Disposition = attachment.Disposition
  287. // });
  288. // });
  289. // }
  290. // return email;
  291. //}
  292. /// <summary>
  293. /// Writes the specified <see cref="DiligEmail"/> object to the underlying database.
  294. /// </summary>
  295. /// <param name="email"></param>
  296. /// <exception cref="ArgumentException"></exception>
  297. /// <exception cref="Exception"></exception>
  298. /// <returns></returns>
  299. //public async Task<int> WriteEmailToDbAsync(DiligEmail email)
  300. //{
  301. // try
  302. // {
  303. // if (email == null)
  304. // {
  305. // throw new ArgumentNullException(nameof(email), "Email can not be null");
  306. // }
  307. // _entities.DiligEmails.Add(email);
  308. // var result = await _entities.SaveChangesAsync();
  309. // return result;
  310. // }
  311. // catch (Exception e)
  312. // {
  313. // throw new Exception("Failed to write entry into the database", e);
  314. // }
  315. //}
  316. /// <summary>
  317. /// Writes the specified <see cref="DiligEmail"/> object to the underlying database.
  318. /// </summary>
  319. /// <param name="email"></param>
  320. /// <exception cref="ArgumentNullException"></exception>
  321. /// <exception cref="Exception"></exception>
  322. /// <returns></returns>
  323. //public int WriteEmailToDb(DiligEmail email)
  324. //{
  325. // try
  326. // {
  327. // if (email == null)
  328. // {
  329. // throw new ArgumentNullException(nameof(email), "Email can not be null");
  330. // }
  331. // _entities.DiligEmails.Add(email);
  332. // var result = _entities.SaveChanges();
  333. // return result;
  334. // }
  335. // catch (ArgumentException)
  336. // {
  337. // throw;
  338. // }
  339. // catch (Exception e)
  340. // {
  341. // throw new Exception("Failed to write entry into the database", e);
  342. // }
  343. //}
  344. }
  345. }