Search code examples
c#emailsmtpmemorystream

Attach a file from MemoryStream to a MailMessage in C#


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.


Solution

  • Here is the sample code.

    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
    writer.Write("Hello its my sample file");
    writer.Flush();
    writer.Dispose();
    ms.Position = 0;
    
    System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
    System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
    attach.ContentDisposition.FileName = "myFile.txt";
    
    // I guess you know how to send email with an attachment
    // after sending email
    ms.Close();
    

    Edit 1

    You can specify other file types by System.Net.Mime.MimeTypeNames like System.Net.Mime.MediaTypeNames.Application.Pdf

    Based on Mime Type you need to specify correct extension in FileName for instance "myFile.pdf"