Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // *** Send all e-mails according to data in database ***
- [HttpPost("[action]")]
- public ActionResult SendAllNotifications()
- {
- var client = new SmtpClient("127.0.0.1", 25);
- var sender = "admin@my-cool-webapi.com";
- try
- {
- var unsentNotifications =
- _dbContext.Notifications.Where(
- x => !x.SentAt.HasValue);
- foreach (var notification in unsentNotifications)
- {
- try
- {
- var mail = new MailMessage(
- from: new MailAddress(sender),
- to: new MailAddress(notification.Receiver));
- mail.Subject = notification.Subject;
- mail.Body = notification.Body;
- client.Send(mail);
- notification.SentAt = DateTime.UtcNow;
- _dbContext.SaveChanges();
- }
- catch (Exception)
- {
- // Black hole for notification is bad handling :(
- }
- }
- return Ok();
- }
- catch (Exception)
- {
- return StatusCode(StatusCodes.Status500InternalServerError);
- }
- }
- // *** Model to send batch of e-mails according to data in database
- public partial class SendNotificationsResponse
- {
- public int SuccessCount { get; set; }
- public int FailCount { get; set; }
- }
- // *** Send batch of e-mails according to data in database ***
- [HttpPost("[action]/{count}")]
- public ActionResult<SendNotificationsResponse> SendNotificationBatch(int? count)
- {
- var client = new SmtpClient("127.0.0.1", 25);
- var sender = "admin@my-cool-webapi.com";
- try
- {
- var unsentNotifications =
- _dbContext.Notifications
- .Where(x => !x.SentAt.HasValue)
- .OrderBy(x => x.CreatedAt)
- .AsQueryable();
- if(count.HasValue)
- unsentNotifications = unsentNotifications.Take(count.Value);
- int sendSuccessCount = 0;
- int sendFailCount = 0;
- foreach (var notification in unsentNotifications)
- {
- try
- {
- var mail = new MailMessage(
- from: new MailAddress(sender),
- to: new MailAddress(notification.Receiver));
- mail.Subject = notification.Subject;
- mail.Body = notification.Body;
- client.Send(mail);
- notification.SentAt = DateTime.UtcNow;
- _dbContext.SaveChanges();
- sendSuccessCount++;
- }
- catch (Exception)
- {
- sendFailCount++;
- }
- }
- return Ok(new SendNotificationsResponse
- {
- SuccessCount = sendSuccessCount,
- FailCount = sendFailCount
- });
- }
- catch (Exception)
- {
- return StatusCode(StatusCodes.Status500InternalServerError);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement