I am writing a program to attach a file to email. Currently I am saving file using FileStream
into disk, and then I use
System.Net.Mail.MailMessage.Attachments.Add(
new System.Net.Mail.Attachment("file name"));
I do not want to store file in disk, I want to store file in memory and from memory stream pass this to Attachment
.
A bit of a late entry - but hopefully still useful to someone out there:-
Here's a simplified snippet for sending an in-memory string as an email attachment (a CSV file in this particular case).
The StreamWriter and underlying stream should not be disposed until after the message has been sent (to avoid
ObjectDisposedException: Cannot access a closed Stream
).I think this code will help you:
I landed on this question because I needed to attach an Excel file I generate through code and is available as
MemoryStream
. I could attach it to the mail message but it was sent as 64Bytes file instead of a ~6KB as it was meant. So, the solution that worked for me was this:Setting the value of
attachment.ContentDisposition.Size
let me send messages with the correct size of attachment.If you actually want to add a .pdf, I found it also necessary to set the position of the memory stream to Zero.
If all you're doing is attaching a string, you could do it in just 2 lines:
I wasn't able to get mine to work using our mail server with StreamWriter.
I think maybe because with StreamWriter you're missing a lot of file property information and maybe our server didn't like what was missing.
With Attachment.CreateAttachmentFromString() it created everything I needed and works great!
Otherwise, I'd suggest taking your file that is in memory and opening it using MemoryStream(byte[]), and skipping the StreamWriter all together.
use OTHER OPEN memorystream:
example for lauch pdf and send pdf in MVC4 C# Controller