循环遍历SmtpClient.Send()

时间:2012-01-31 17:22:40

标签: c# asp.net email smtpclient

我正在开发一个ASP.NET(C#)产品,该产品必须将uniq电子邮件发送到订阅者列表。我的代码看起来像这样:

// Grab subscribers from db, about 10-20.
var malingList = Bll.GetAllSubscribers();
var client = new SmtpClient(); 

// Set up settings on the SmtpClient with cridentails and so on

foreach(var subscriber in mailingList)
{
  var message = new MailMessage(); 
  // Set up message, set reciver, yada yada
  Client.Send(message);
}

client.Dispose();

使用“假smtp”Papercut进行测试时出现此错误:发送邮件失败。无法将数据写入传输连接:

我想要做的是保持SMTP连接打开。不必为每封电子邮件重现“握手”。

我不是100肯定但是。这有用吗?我想我有另一个项目,它实现了这个。

2 个答案:

答案 0 :(得分:0)

我猜这可能与smtp客户端发送批量邮件的限制有关。 也许你可以在20-30封邮件之后不时处理客户端?

答案来自: Failure sending mail. Unable to write data to the transport connection

答案 1 :(得分:0)

Papercut库将无法为您正在寻找的行为提供便利,因为每次调用Send时,它都将丢弃当前连接并建立与服务器的另一个连接并进行握手。以下是CodePlex存储库的来源:

public void Send()
{
    string response;

    Connect(session.Sender, 25);
    response = Response();
    if (response.Substring(0, 3) != "220")
        throw new SmtpException(response);

    Write("HELO {0}\r\n", Util.GetIPAddress());
    response = Response();
    if (response.Substring(0, 3) != "250")
        throw new SmtpException(response);

    Write("MAIL FROM:<{0}>\r\n", session.MailFrom);
    response = Response();
    if (response.Substring(0, 3) != "250")
        throw new SmtpException(response);

    session.Recipients.ForEach(address =>
        {
            Write("RCPT TO:<{0}>\r\n", address);
            response = Response();
            if (response.Substring(0, 3) != "250")
                throw new SmtpException(response);
        });

    Write("DATA\r\n");
    response = Response();
    if (response.Substring(0, 3) != "354")
        throw new SmtpException(response);

    NetworkStream stream = GetStream();
    stream.Write(session.Message, 0, session.Message.Length);

    Write("\r\n.\r\n");
    response = Response();
    if (response.Substring(0, 3) != "250")
        throw new SmtpException(response);

    Write("QUIT\r\n");
    response = Response();
    if (response.IndexOf("221") == -1)
        throw new SmtpException(response);
}

当然,您可以在考虑开源之后更改源代码以执行您的操作。