c# - 发送 2000 封电子邮件

标签 c# smtpclient

实例化一个 SMTP 客户端一次并在其上同步发送 2,000 封电子邮件是否可以?

当使用本文末尾粘贴的代码为我们发送的每条消息实例化 SMTP 客户端时,我们收到以下错误:

System.Net.Mail.SmtpException: Service not available, closing transmission channel. The server response was: 4.4.1 Connection timed out

我怀疑为每封邮件实例化 SMTP 客户端都会导致此问题,但不确定。 代码如下。

List<MailMessage> messages = GetMailMessages();
foreach( MailMessags m in messages)
{
    try
    {
        SmtpClient client = new SmtpClient();//SHOULD THIS BE PLACED OUTSIDE AND BEFORE THE LOOP
        client.Send(m);
    }
    catch (Exception)
    {
        throw;
    }
}

编辑1:

我刚刚在 MSDN 上找到了这个。 (http://msdn.microsoft.com/en-us/library/ee706942%28v=vs.110%29.aspx)。 因此,教训似乎是,在使用群发电子邮件时,您必须仅实例化 SMTP 客户端一次,然后将其重新用于所有多个 MailMessage。

The connection established by the current instance of the SmtpClient class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is
particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts.

最佳答案

你真的应该善待你的邮件服务器,但 SMTP 客户端可以处理不止一封电子邮件,如果你像这样异步执行此操作,你会更好地利用你的服务器硬件......

async Task SendMail(ICollection<MailMessage> messages)
{
    using (var client = new SmtpClient())
    {
        foreach (MailMessags m in messages)
        {
            try
            {
                await client.SendAsync(m);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

我怀疑目前抛出异常的原因是由于重复的连接尝试,因此服务器可能“表现出”作为一种手段来表示“停止用重复的连接来戳我”。

上面的代码示例将确定代表您建立多少个连接,并与服务器进行更“礼貌”的通信,同样正如您所指出的,文档指出了这种方法更适合的其他一些场景.

关于c# - 发送 2000 封电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21894671/

相关文章:

c# - Tizen xamarin webview 应用程序在启动时关闭

javascript - 使用无法在 javascript 代码中访问的 AjaxEnabled WCF 服务

c# - 无法使用 DeflateStream 与 C# 一起膨胀

c# - 无法使用 GoDaddy 配置的 Office 365 帐户中的 C# 代码发送电子邮件

c++ - 使用 SMTPS (TLS) 通过 gmail (smtp.gmail.com) 发送电子邮件的开源库

c# - 如何使用静态数据填充 View 模型

c# - 将带逗号的字符串转换为 double

c# - 将已发送的 MailMessage 获取到 "Sent Folder"

C# Winforms 应用程序发送电子邮件失败 : The remote name could not be resolved: 'smtp. gmail.com ;操作超时

c# - 使用 SmtpClient 发送邮件时出现 "The server committed a protocol violation"故障排除