Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you send mass emails from ASP.NET?

I built a website for a client and they would like a custom newsletter tool. Building the tool was easy, but I'm not sure how to send the email.

I set up a test page and managed to send a test email to myself using the System.Net.Mail namespace. I tried applying this code to a loop on the newsletter page, but it's turning out to be quite a difficult task. The email sending loop locks up the whole site for about an hour while it sends its emails. Sometimes it will abort the loop midway and some of the emails won't get sent.

I tried starting the loop on another thread.

protected void btnSendNewsletter_Click(object sender, EventArgs e)
{
    Thread t = new System.Threading.Thread(new ThreadStart(SendEmails));
    t.Start();
}

but this still makes the site go slow and also has a habit of aborting part way through. What is the common method for sending mass emails? I'm sure I'm not doing it right.

I am very new to the email arena in .NET.

like image 257
Chev Avatar asked May 05 '11 18:05

Chev


1 Answers

For this kind of task you're better to add a bunch of jobs to a queue. Then have a thread running which pulls x number of jobs from the queue, processes them (i.e. sends the emails) and then sleeps for a period of time. This will give you web app some breathing space.

If you're using a database you can create an Email Queue table to store the jobs. I prefer to use this kind of storage over memory incase the app recycles for some reason or an exception is thrown...atleast you can then pick up from where you left off.

Generally, the process running the worker thread wouldn't be the web app itself. It would be a windows service or something similar. This might not be possible if you're on shared hosting.

like image 186
Lee Gunn Avatar answered Nov 16 '22 00:11

Lee Gunn