问题描述
当我使用 System.Net.Mail 发送邮件时,邮件似乎不会立即发送.他们需要一两分钟才能到达我的收件箱.一旦我退出应用程序,所有消息都会在几秒钟内收到.是否有某种邮件消息缓冲区设置可以强制 SmtpClient 立即发送消息?
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);
}
谢谢,
标记
推荐答案
如果你在 Dotnet 4.0 上试试这个
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);
}
这将释放您的 client
实例,使其使用 QUIT 协议元素结束其 SMTP 会话.
This will Dispose your client
instance, causing it to wrap up its SMTP session with a QUIT protocol element.
如果您卡在较早的 dotnet 版本上,请尝试安排为您的程序发送的每条消息重新使用相同的 SmtpClient 实例.
If you're stuck on an earlier dotnet version, try arranging to re-use the same SmtpClient instance for each message your program sends.
当然,请记住,电子邮件本质上是一个存储转发系统,从 smtp 发送到接收的延迟没有任何同步(甚至是正式可预测的).
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.
这篇关于System.Net.Mail 和 MailMessage 不立即发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!