问题
I'm working on a ASP.NET (C#) product that has to send uniq emails to a list of subscribers. My code looks something like this:
// 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();
I get this error when testing this with the "fake smtp" Papercut: Failure sending mail.Unable to write data to the transport connection:
What I want to do is to keep the SMTP-connection open aka. don't have to reproduce the "handshake" with every e-mail.
I'm not 100 sure but. Should this work? I think I have another project where it's implemented as this.
回答1:
The Papercut library will not be able to facilitate the behavior you're looking for because each time you call Send
it will drop the current connection and establish another connection to the server and do the handshake anyway. Here's the source from their CodePlex repository:
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);
}
You could of course change the source to do what you are after considering it is open source.
回答2:
I guess it could have some relation with the limitation of the smtp client to send bulk mails. Maybe you could dispose the client so now and then, after 20-30 mails?
Answer gotten from: Failure sending mail. Unable to write data to the transport connection
来源:https://stackoverflow.com/questions/9083991/loop-over-smtpclient-send