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?