简体   繁体   中英

Running a background task for sending emails when a user posts to a discussion board in ASP.NET CORE

I need to send emails via SMTP to all subscribers of a discussion board. If there a lot (say 1000+) subscribers, I do not want the users who posts a new post to have to wait while the notification emails are being sent out.

At first I thought I could use: System.Net.Mail.SmtpClient.SendMailAsync

But, as this post explains , "Async is not a magic wand that makes the action return the response quicker. Your task (in this case, sending an email) takes as long as it takes and async or not, the action will not return a response until the task has completed." Async is more about being efficient with threads than it is about making a task run faster.

First, is my research about SendMailAsync correct? I don't think it is a correct solution.

Second, what would be a way to achieve my goal? A background task ? I've heard of Hangfire . Is something like Hangfire what I need to use? Or could I just use an AJAX call to send the emails?

Btw, I'm using ASP.NET Core and .NET Framework 4.6.1

How about using a message queue service (eg RabbitMQ or AWS SQS) running on a separate server? then post a message to that server with details of what needs to be done (in this case what to send to whom), and then the message service can pull messages off the queue at its leisure, process them (send out 1000s of emails) and then get the next thing off the queue.

I used hangfire in a similar situation. Here's how I implemented it.

  1. Stored the list of emails to be sent in the database.
  2. Used hangfire to process the emails in the background.

You could use a separate queue/server for the processing. Did the job for me.

Check this post on Background Processing in ASP.net using Hangfire

Also, go through the hangfire best practices before implementing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM