When I sent a mail using System.Net.Mail, it seems that the messages do not send immediately. They take a minute or two before reaching my inbox. Once I quit the application, all of the messages are received within seconds though. Is there some sort of mail message buffer setting that can force SmtpClient to send messages immediately?
public static void SendMessage(string smtpServer, string mailFrom, string mailFromDisplayName, string[] mailTo, string[] mailCc, string subject, string body)
{
try
{
string to = mailTo != null ? string.Join(",", mailTo) : null;
string cc = mailCc != null ? string.Join(",", mailCc) : null;
MailMessage mail = new MailMessage();
SmtpClient client = new SmtpClient(smtpServer);
mail.From = new MailAddress(mailFrom, mailFromDisplayName);
mail.To.Add(to);
if (cc != null)
{
mail.CC.Add(cc);
}
mail.Subject = subject;
mail.Body = body.Replace(Environment.NewLine, "<BR>");
mail.IsBodyHtml = true;
client.Send(mail);
}
catch (Exception ex)
{
logger.Error("Failure sending email.", ex);
}
Thanks,
Mark
SmtpClient
pools connections. Consequently, theSmtpClient
instance does not know when you are done.Dispose
tells theSmtpClient
instance you are done and to send aQUIT
message on all of the established connections, followed by closing the TCP connections and then freeing the sockets. Thus, wrap your usage ofSmtpClient
in ausing
block or add afinally
block where you invokeSmtpClient.Dispose
. – Glyptography