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 13KB

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