Email Queue
by Joseph on May 3rd in C#, EMail, QUEUE, SMTP
So I was thinking about the situation of one of the websites I work with. The website is on a separate server from the SMTP server, so requests for information, purchases, etc. risk getting dead air.
I chose to solve this problem by setting up a fairly simple queue on the web server. Essentially, any time someone sends an email, it tries to send anything on the queue. If it can’t, then things stay on the queue a little longer. During a typical server reboot, this should accumulate a half dozen emails or so before the SMTP server is back online.
Here’s the code. I’d love to hear your thoughts! If you copy\paste, I would appreciate if you could leave our company information in the comments.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;namespace IntentDrivenClassLibrary
// library developed by Intent Driven Designs
// http://www.IntentDriven.com
// copyright 2009
// free to use – post back any changes – do not remove this comment
// posted on http://blog.intentdriven.com
{
public static class IDDSendMail
{
private static QueueMessages = new Queue (); public static MailMessage Message
{
set
{
Messages.Enqueue(value);
while (Messages.Count > 0)
{
MailMessage msg = Messages.Dequeue();
try
{
SmtpSendEmail(msg);
}
catch (Exception)
{
Messages.Enqueue(msg);
break;
}
}
}
}private static void SmtpSendEmail(MailMessage msg)
{
SmtpClient client = new SmtpClient(“localhost”)
{
Port = 587,
Credentials = new NetworkCredential(“[emailaccount]”,”[emailpassword]”)
};
client.Send(msg);
}
}
}