Home > Backend Development > C++ > How to Attach Files to Emails using MemoryStream in C#?

How to Attach Files to Emails using MemoryStream in C#?

Mary-Kate Olsen
Release: 2025-01-02 16:06:39
Original
506 people have browsed it

How to Attach Files to Emails using MemoryStream in C#?

Using MemoryStream to Attach Files to MailMessage in C

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.

Solution

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();
Copy after login

Customization

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template