Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Net.Mail and MailMessage not Sending Messages Immediately

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

like image 275
mservidio Avatar asked Sep 13 '11 14:09

mservidio


People also ask

What is System Net mail?

Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). The SmtpClient type is obsolete on some platforms and not recommended on others; for more information, see the Remarks section.

What is SMTP exception?

SMTP is an internet standard used by mail servers to send and receive email. SMTP error messages help you understand why a message wasn't sent successfully. If incoming or outgoing messages are bouncing, check the bounce messages for an SMTP error code that can help you diagnose the problem.

What is MailMessage in asp net?

Instances of the MailMessage class are used to construct email messages that are transmitted to an SMTP server for delivery using the SmtpClient class. The sender, recipient, subject, and body of an email message may be specified as parameters when a MailMessage is used to initialize a MailMessage object.


1 Answers

Try this, if you're on Dotnet 4.0

using (SmtpClient client = new SmtpClient(smtpServer))  
{
    MailMessage mail = new MailMessage();
    // your code here.

    client.Send(mail);
}

This will Dispose your client instance, causing it to wrap up its SMTP session with a QUIT protocol element.

If you're stuck on an earlier dotnet version, try arranging to re-use the same SmtpClient instance for each message your program sends.

Of course, keep in mind that e-mail is inherently a store-and-forward system, and there is nothing synchronous (or even formally predictable) about delays from smtp SEND to reception.

like image 178
O. Jones Avatar answered Sep 30 '22 19:09

O. Jones