Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an Email queue mechanism in ASP.NET In case of network goes down?

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("[email protected]");
            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("[email protected]", "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?

like image 452
Prageeth Liyanage Avatar asked Aug 25 '15 04:08

Prageeth Liyanage


People also ask

How do I create a queue service?

Create queuing services There are two methods, one that exposes queuing functionality, and another that dequeues previously queued work items. A work item is a Func<CancellationToken, ValueTask> . Next, add the default implementation to the project. The preceding implementation relies on a Channel<T> as a queue.

How can you send an email message from an asp net web page?

First: Edit Your AppStart Page SmtpPort: The port the server will use to send SMTP transactions (emails). EnableSsl: True, if the server should use SSL (Secure Socket Layer) encryption. UserName: The name of the SMTP email account used to send the email. Password: The password of the SMTP email account.

What is a queue email?

An email queue decouples the sender from the recipient. It allows them to communicate without being connected. As such, the queued emails wait for processing until the recipient is available to receive them. You can look at an email queue as a buffer where the emails are stored before they hit the endpoint.

What is ASP Net queue?

ASP.NET Queue The Queue works like FIFO system , a first-in, first-out collection of Objects. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is we will get the reference of first item ) item from Queue.


1 Answers

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.

like image 159
Saeb Amini Avatar answered Sep 28 '22 00:09

Saeb Amini