System.Net.Mail and MailMessage do not send messages immediately

When I sent mail using System.Net.Mail, it seems that messages are not sent immediately. They take a minute or two before reaching my inbox. As soon as I exit the application, all messages are received within a few seconds. Is there some kind of message buffer setting that could cause 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

+6
source share
2 answers

Try it if you are in Dotnet 4.0

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

This will delete your client instance, forcing it to end the SMTP session using the QUIT protocol element.

If you are stuck with an earlier version of dotnet, try reusing the same instance of SmtpClient for each message your program sends.

Of course, keep in mind that email is essentially a store-and-forward system, and there is nothing synchronous (or even formally predictable) about delays with smtp SEND on reception.

+10
source

I agree with Ollie. To answer your question, no, I do not believe that there is any buffer setting that you can set through the form.

What makes you embarrassed by your question, you say that a message takes a minute or two to reach your inbox, but then continue to say that when they send themselves, they go instantly ... I suppose you mean that internally , messages are sent in a fine, and the problem occurs only for the external address. In this case, it seems that your mail server may overturn these messages for other email addresses associated with external addresses (which is normal activity). Waiting a minute or two for e-mail on an external site is not so long.

However, this is unlikely, but is your Exchange server installed to scan outgoing messages?

0
source

Source: https://habr.com/ru/post/897239/


All Articles