When composing emails, it's often necessary to attach files. Typically, developers save the file to disk using FileStream and then attach it using the MailMessage.Attachments.Add() method. However, an alternative approach involves storing the file in memory using MemoryStream and passing it directly to an Attachment object.
To achieve this, follow the steps outlined in the sample code below:
// Create a MemoryStream and populate it with the file content 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; // Define the file type based on MIME type System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain); ct.Parameters.Add("name", "myFile.txt"); // Set the attachment filename, including extension // Create an Attachment object from the MemoryStream System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct); // Attach the file to the email message mailMessage.Attachments.Add(attach); // Send the email, assuming you have an existing `mailMessage` object mailMessage.Send(); // Close the MemoryStream after sending the email ms.Close();
Depending on the file type, you can specify different MIME types. For example, to attach a PDF file, use System.Net.Mime.MediaTypeNames.Application.Pdf.
Ensure that the FileName property of the Attachment object matches the specified MIME type. In the above example, we specify "myFile.txt" when using the MediaTypeNames.Text.Plain MIME type.
The above is the detailed content of How to Attach Files to Emails using MemoryStream in C#?. For more information, please follow other related articles on the PHP Chinese website!