I'm trying to send a mail message using System.Net.Mail.SmtpClient
with SSL enabled. While changing no external factors (i.e. hit F5, then hit F5 Again - or even in a loop) it works some times, but most of the times it fails.
Example code:
public void SendMail()
{
using (var client = new SmtpClient())
{
MailMessage mailMessage = new MailMessage();
client.EnableSsl = true;
client.Host = "smtp.example.com";
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
mailMessage.From = new MailAddress("from@example.com");
mailMessage.To.Add(new MailAddress("to@example.com"));
mailMessage.Subject = "Test";
mailMessage.Body = "Message " + DateTime.Now.ToString();
try
{
client.Send(mailMessage);
}
catch (Exception ex)
{
// This being a Pokemon block is besides the point
}
}
}
In my catch block I just get a timeout, but if I set up a trace for System.Net
and System.Net.Sockets
I can see a number of different exceptions:
- Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall
- Unable to read data from the transport connection: An established connection was aborted by the software in your host machine
- Cannot access a disposed object
- Reading is not supported on this stream
- Writing is not supported on this stream
All of which happen post EHLO, STARTTLS and authentication. The client and the server are chatting along in their cryptographic ways when the exceptions are thrown.
System.Net.Mail.SmtpClient.Send()
is the the only frame all call stacks have in common.
Of course I've tried changing the code in a number of ways, such as setting client.UseDefaultCredentials
, using client.SendAsync()
and whatnot. But I suspect it's something entirely different knocking the connection over at different times - a configuration error on one of the machines involved perhaps?
So I've checked the Event Logs for signs of something messing with the connection, but I haven't found anything.
Any suggestions as to what I should be looking for here?