I’m trying to fill a queue with user’s mails to send confirmation mails to them after a period of time, so every time any user fill his registration form I add him to the queue in order to send mails to them after about one minute and here is my code
public static class Gmail
{
private static int ? date;
public static bool SendMail(string AdminMail,string AdminPassword,string subject,string toAddress, string content,DateTime SendTime)
{
var toAddressList = new Queue<string>();
toAddressList.Enqueue(toAddress);
if(date==null)
{
date = DateTime.Now.Second;
}
if (date-SendTime.Second > 120)
{
var message = new MailMessage
{
From = new MailAddress(AdminMail)
};
foreach (var toAddressl in toAddressList)
{
message.To.Add(new MailAddress(toAddressl));
}
message.Subject = subject;
message.Body = content;
message.IsBodyHtml = true;
var smtp = new SmtpClient
{
Credentials = new System.Net.NetworkCredential(AdminMail, AdminPassword),
Port = 587,
Host = "smtp.gmail.com",
EnableSsl = true
};
smtp.Send(message);
//date = SendTime;
return true;
}
return false;
}
}
but actually what happens is that the queue starts from zero every time, so it is only filled with the mail of the current registered users and never contain the mails of the previous registered users which I want them to exist as I will send mails to all mails existing in the queue.So I’m wondering how I can prevent the queue from been cleared when the page loads.Any ideas??
toAddress is defined with the scope of the static method. It will only exist for the duration of that method call. That’s why it’s always 0.
You could push it up to be a static field or property (i.e. alongside your date property) but you are still going to have issues with this; for example, what if the app pool is recycled or the website restarts? You are going to lose everything in the queue.
A more robust design would involve storing this information in a database and running a scheduled check against those records that were recently added and don’t have a “confirm email sent” column value set, for example.