System.Net.Mail 和 MailMessage 不立即发送消息

System.Net.Mail and MailMessage not Sending Messages Immediately(System.Net.Mail 和 MailMessage 不立即发送消息)
本文介绍了System.Net.Mail 和 MailMessage 不立即发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 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 不立即发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)