MemoryStream Mail Attachments in .NET 2.0

I was having some odd errors sending MemoryStreams as email attachments and I wasn’t finding samples on the web that worked (or compiled). I was finally able to figure out that the MemoryStream needs to be open in order for the send to go through, like so:

string from = “ben@foobar.com”;
string to = “you@foobar.com”;
string subject = “my email”;
string body = “this is an email with an attachment.”;
MailMessage mail = new MailMessage(from, to, subject, body);
System.IO.MemoryStream memorystream = new System.IO.MemoryStream();
System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(memorystream);
streamwriter.Write(“Hello world!”);
mail.Attachments.Add(new Attachment(memorystream, “test.txt”, System.Net.Mime.MediaTypeNames.Text.Plain));
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
streamwriter.Close();
streamwriter.Dispose();
memorystream.Dispose();


 

If the Stream is closed you’ll get a System.Net.Mail.SmtpException whose InnerException says “Cannot access a closed Stream.”

0