循环遍历SmtpClient.Send()

我正在开发一个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肯定但是。 这有用吗? 我想我有另一个项目,它实现了这个。

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); } 

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

我想这可能与smtp客户端发送批量邮件的限制有某种关系。 也许你可以在20-30封邮件后偶尔处理客户端?

答案来自: 发送邮件失败。 无法将数据写入传输连接