I got a exception while sending a mail that The request was aborted: The connection was closed unexpectedly. I don’t know why it is happening.. After some researching i got a point that this is because i am disposing http response object before reading from its stream.
Code i got exception
using(Stream stream = req.GetResponse().GetResponseStream()){
if (stream != null)
{
attachment = new Attachment(stream, ct);
message.Attachments.Add(attachment);
}
}
Send mail after disposing the stream object
client.Send(message);
Solution
Don’t try to pass the stream object after disposing. The using statement obtains the resource specified, executes the statements and finally calls the Dispose
method of the object to clean up the object.
Corrected Code
using(Stream stream = req.GetResponse().GetResponseStream()){
if (stream != null)
{
attachment = new Attachment(stream, ct);
message.Attachments.Add(attachment);
client.Send(message);
}
}
Enjoy coding…