home · blog · groups · about us · contact us
DevelopmentNow Blog
 Wednesday, October 11, 2006
 
 

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."


October 11, 2006    Bookmark to Digg or other social bookmarking
#    Disclaimer  |  Comments [2]

Related posts:
iPhone Webapp Development for ASP.NET
Firefox 3.0.1 and FileUpload validator issues
Parse CSV Files in C# and ASP.NET
Visual Studio 2008 Virtual PC Performance Tips
Linq to SQL: Cast Stored Procedure Results to Table Entities
Grouping in Linq to SQL vs SQL


« EnableViewState for User Controls and AS... | Main | How to Renew your Microsoft Empower for ... »
Friday, October 13, 2006 10:11:14 AM (Pacific Standard Time, UTC-08:00)
streamwriter.Close(); is an overload for streamwriter.Dispose();, negating the need to call streamwriter.Dispose();.
James Johnson
Wednesday, October 18, 2006 7:28:39 AM (Pacific Standard Time, UTC-08:00)
Ah, thanks for the tip, James. I guess that would explain why calling .Close() before attaching it to the email would fail. :)

As far as calling .Dispose() after .Close(), I guess I've just gotten into the habit of calling Dispose() on anything that implements IDisposable just to make sure. Or I use the "using" keyword.
Comments are closed.