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

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