| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388 |
- using System.Net.Mail;
- using System.Net;
- using Diligent.WebAPI.Contracts.Models;
-
- namespace Diligent.WebAPI.Business.Services
- {
- /// <summary>
- /// Provieds an API for sending emails in both sync & async fashion, as well as sending emails with delays.
- /// </summary>
- public class Emailer : IEmailer
- {
- private readonly MailSettings _settings;
-
- public Emailer(IOptions<MailSettings> mailSettings)
- {
- _settings = mailSettings.Value;
- //_settings = new AuthorizationSettings
- //{
- // SmtpServer = "smtp.mailtrap.io",
- // SmtpPort = 2525,
- // SmtpUseSSL = true,
- // SmtpUsername = "460e3c49f02e37",
- // SmtpPassword = "66443869eaad55",
- // SmtpFrom = "noreply@hrcenter.net",
- // SmtpFromName = "HRCenter Team"
- //};
- }
-
- /// <summary>
- /// Sends an email asynchronously and inserts a new <see cref="DiligEmail"/> record to the underlying database.
- /// </summary>
- /// <param name="to"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- /// <param name="isHtml"></param>
- /// <param name="attachments"></param>
- /// <param name="cc"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <see cref="ArgumentNullException"/>
- /// <exception cref="Exception"></exception>
- /// <returns></returns>
- public async Task<bool> SendEmailAndWriteToDbAsync(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null)
- {
- var emailResult = await SendEmailAsync(to, subject, body, isHtml, cc);
-
- var email = CreateEmail(to, subject, body, isHtml);
-
- if (emailResult)
- {
- email.SentTime = DateTime.UtcNow;
- }
-
- //var dbResult = await WriteEmailToDbAsync(email);
-
- return emailResult; // && dbResult > 0;
- }
-
- public async Task<bool> SendEmailAndWriteToDbAsync(string to, string subject, string body, bool isHtml = false, List<string> cc = null)
- {
- return await SendEmailAndWriteToDbAsync(new List<string> { to }, subject, body, isHtml, cc);
- }
-
- /// <summary>
- /// Sends an email synchronously and inserts a new <see cref="DiligEmail"/> record to the underlying database.
- /// </summary>
- /// <param name="to"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- /// <param name="isHtml"></param>
- /// <param name="attachments"></param>
- /// <param name="cc"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <see cref="ArgumentNullException"/>
- /// <exception cref="Exception"></exception>
- /// <returns></returns>
- public bool SendEmailAndWriteToDb(List<string> to, string subject, string body, bool isHtml = false,
- List<string> cc = null)
- {
- var emailResult = SendEmail(to, subject, body, isHtml, cc);
-
- var email = CreateEmail(to, subject, body, isHtml);
-
- if (emailResult)
- {
- email.SentTime = DateTime.UtcNow;
- }
-
- //var dbResult = WriteEmailToDb(email);
-
- return emailResult; // && dbResult > 0;
- }
-
- public bool SendEmailAndWriteToDb(string to, string subject, string body, bool isHtml = false,
- List<string> cc = null)
- {
- return SendEmailAndWriteToDb(new List<string> { to }, subject, body, isHtml, cc);
- }
-
- /// <summary>
- /// Sends an email synchronously.
- /// </summary>
- /// <param name="to"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- /// <param name="isHtml"></param>
- /// <param name="attachments"></param>
- /// <param name="cc"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <see cref="ArgumentNullException"/>
- /// <exception cref="Exception"></exception>
- /// <returns></returns>
- public bool SendEmail(List<string> to, string subject, string body, bool isHtml = false,
- List<string> cc = null)
- {
- try
- {
- using (var smtp = GetSmtpClient())
- {
- var message = GetMailMessage(to, subject, body, isHtml, cc);
-
- smtp.Send(message);
-
- return true;
- }
- }
- catch (ArgumentException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new Exception("Failed to send email message.", e);
- }
- }
-
- /// <summary>
- /// Sends an email asynchronously.
- /// </summary>
- /// <param name="to"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- /// <param name="isHtml"></param>
- /// <param name="attachments"></param>
- /// <param name="cc"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <see cref="ArgumentNullException"/>
- /// <exception cref="Exception"></exception>
- /// <returns></returns>
- public async Task<bool> SendEmailAsync(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null)
- {
- try
- {
- using (var smtp = GetSmtpClient())
- {
- var message = GetMailMessage(to, subject, body, isHtml, cc);
-
- await smtp.SendMailAsync(message);
-
- return true;
- }
- }
- catch (ArgumentException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new Exception("Failed to send email message.", e);
- }
- }
-
- /// <summary>
- /// Creates a <see cref="SmtpClient"/> object and configures it.
- /// </summary>
- /// <returns></returns>
- public SmtpClient GetSmtpClient()
- {
- var smtp = new SmtpClient(_settings.SmtpServer) { Timeout = 1000000 };
-
- if (!string.IsNullOrWhiteSpace(_settings.SmtpUsername))
- {
- smtp.UseDefaultCredentials = false;
- smtp.Credentials = new NetworkCredential(
- _settings.SmtpUsername,
- _settings.SmtpPassword);
- smtp.EnableSsl = _settings.SmtpUseSSL;
- smtp.Port = _settings.SmtpPort;
- }
-
- return smtp;
- }
-
- /// <summary>
- /// Creates a new <see cref="MailMessage"/> from the specified arguments.
- /// </summary>
- /// <param name="to"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- /// <param name="isHtml"></param>
- /// <param name="attachments"></param>
- /// <param name="cc"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <returns></returns>
- public MailMessage GetMailMessage(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null)
- {
- var message = new MailMessage
- {
- Sender = new MailAddress(_settings.SmtpFrom, _settings.SmtpFromName),
- From = new MailAddress(_settings.SmtpFrom),
- Subject = subject,
- Body = body,
- IsBodyHtml = isHtml
- };
-
-
-
- if (to.Any())
- {
- message.To.Add(string.Join(",", to.Where(email => !string.IsNullOrWhiteSpace(email))));
- }
- else
- {
- throw new ArgumentException("The list of recipient emails can not be empty");
- }
-
- if (cc != null && cc.Any())
- {
- message.CC.Add(string.Join(",", cc.Where(email => !string.IsNullOrWhiteSpace(email))));
- }
-
- return message;
- }
-
- /// <summary>
- /// 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.
- /// </summary>
- /// <param name="to"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- /// <param name="isHtml"></param>
- /// <param name="attachments"></param>
- /// <param name="dontSendBefore"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <exception cref="Exception"></exception>
- /// <returns></returns>
- public async Task<bool> SendEmailWithDelayAsync(List<string> to, string subject, string body, bool isHtml = false, DateTime? dontSendBefore = null)
- {
- try
- {
- var email = CreateEmail(to, subject, body, isHtml, dontSendBefore);
-
- //var result = await WriteEmailToDbAsync(email);
-
- return true;
- }
- catch (ArgumentException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new Exception("Error while attempting to send an email with delay.", e);
- }
- }
-
- /// <summary>
- /// Creates a <see cref="DiligEmail"/> object with specified arguments.
- /// </summary>
- /// <param name="to"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- /// <param name="isHtml"></param>
- /// <param name="attachments"></param>
- /// <param name="dontSendBefore"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <returns></returns>
- public DiligEmail CreateEmail(List<string> to, string subject, string body, bool isHtml = false,
- DateTime? dontSendBefore = null)
- {
- if (!to.Any())
- {
- throw new ArgumentException("The list of recipient emails can not be empty");
- }
- var email = new DiligEmail
- {
- To = to.Aggregate((previous, next) => previous + ";" + next),
- Subject = subject,
- Body = body,
- IsHtml = isHtml,
- DontSendBefore = dontSendBefore,
- CreateTime = DateTime.UtcNow
- };
-
-
-
- return email;
- }
-
- /// <summary>
- /// Fills the specified <see cref="DiligEmail"/> object with the specified <see cref="EmailAttachment"/> list.
- /// </summary>
- /// <param name="email"></param>
- /// <param name="attachments"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <returns></returns>
- //public DiligEmail FillEmailAttachments(DiligEmail email)
- //{
- // if (email == null)
- // {
- // throw new ArgumentNullException(nameof(email), "Email can not be null");
- // }
-
- // if (attachments != null && attachments.Any())
- // {
- // attachments.ForEach(attachment =>
- // {
- // email.DiligEmailAttachments.Add(new DiligEmailAttachment
- // {
- // FileName = attachment.FileName,
- // SourceFileName = attachment.SourceFileName,
- // Type = attachment.Type,
- // Disposition = attachment.Disposition
- // });
- // });
- // }
-
- // return email;
- //}
-
- /// <summary>
- /// Writes the specified <see cref="DiligEmail"/> object to the underlying database.
- /// </summary>
- /// <param name="email"></param>
- /// <exception cref="ArgumentException"></exception>
- /// <exception cref="Exception"></exception>
- /// <returns></returns>
- //public async Task<int> WriteEmailToDbAsync(DiligEmail email)
- //{
- // try
- // {
- // if (email == null)
- // {
- // throw new ArgumentNullException(nameof(email), "Email can not be null");
- // }
- // _entities.DiligEmails.Add(email);
-
- // var result = await _entities.SaveChangesAsync();
-
- // return result;
- // }
- // catch (Exception e)
- // {
- // throw new Exception("Failed to write entry into the database", e);
- // }
- //}
-
- /// <summary>
- /// Writes the specified <see cref="DiligEmail"/> object to the underlying database.
- /// </summary>
- /// <param name="email"></param>
- /// <exception cref="ArgumentNullException"></exception>
- /// <exception cref="Exception"></exception>
- /// <returns></returns>
- //public int WriteEmailToDb(DiligEmail email)
- //{
- // try
- // {
- // if (email == null)
- // {
- // throw new ArgumentNullException(nameof(email), "Email can not be null");
- // }
- // _entities.DiligEmails.Add(email);
-
- // var result = _entities.SaveChanges();
-
- // return result;
- // }
- // catch (ArgumentException)
- // {
- // throw;
- // }
- // catch (Exception e)
- // {
- // throw new Exception("Failed to write entry into the database", e);
- // }
- //}
- }
- }
|