6

I am developing a website by using ASP.NET. In there I am sending emails to users.

Currently I am using this code to send email asynchronously to user. Emails are sending in background.

public static void SendEmail(string Path, string EmailTo)
{
    Thread emailThread = new Thread(delegate()
    {
        try
        {
            string body = string.Empty;
            using (StreamReader reader = new StreamReader(Path))
            {
                body = reader.ReadToEnd();
            }
            MailMessage mail = new MailMessage();

            mail.From = new MailAddress("test@test.com");
            mail.To.Add(EmailTo);
            mail.Subject = "Test email";
            mail.Body += body;
            mail.IsBodyHtml = true;

            SmtpClient smtpClient = new SmtpClient("smtp.test.com");            
            smtpClient.Port = 587;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new System.Net.NetworkCredential("test@test.com", "test");
            smtpClient.EnableSsl = true;

            smtpClient.SendCompleted += (s, e) =>
            {
                smtpClient.Dispose();
                mail.Dispose();
            };
            try
            {
                smtpClient.Send(mail);
            }
            catch (Exception ex) { /* exception handling code here */ }
        }
        catch (Exception)
        {

            throw;
        }
    });
    emailThread.IsBackground = true;
    emailThread.Start();
}

So above code is working fine. But one day I got a problem. When I press the send button at the same time my internet connection was down. So email didn't get fired. Thats the time I realize that this email function need some mechanism to queue the emails and send it to users one by one according to the order in the queue. So if any email got undelivered or if network gets down then retry it. So how to achieve this mechanism?

Prageeth Liyanage
  • 1,612
  • 2
  • 19
  • 41

1 Answers1

6

Decouple the queuing of emails from sending them. e.g.:

  1. Create a database table for outgoing emails, with a column for their Sent date.
  2. Whenever you want to send an outgoing email, insert it into the table with a NULL sent date.
  3. Have a background task run every X seconds to check for emails with a NULL sent date, try sending them, and update their Sent date if successful. HINT: for an easy way to queue recurring tasks in ASP.NET have a look at this.

This is a very stripped to bone simple example, but you can easily expand on it.

Saeb Amini
  • 23,054
  • 9
  • 78
  • 76