Home >Backend Development >C++ >How to Attach Files from a MemoryStream to a MailMessage in C#?

How to Attach Files from a MemoryStream to a MailMessage in C#?

DDD
DDDOriginal
2025-01-02 15:27:39444browse

How to Attach Files from a MemoryStream to a MailMessage in C#?

Attaching Files from MemoryStream to MailMessage in C

When composing emails in C#, you may encounter the need to attach files. Traditionally, files were stored on disk before being added to the attachments collection. However, this approach requires saving files to disk, which can be inefficient and unnecessary in certain scenarios.

Instead of saving files to disk, you can store them in memory using MemoryStream. This technique allows you to directly attach the files to the MailMessage object without intermediary steps.

Code Example

The following code sample demonstrates how to attach a file from MemoryStream to a MailMessage:

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 using System.Net.Mime.MimeTypeNames, such as System.Net.Mime.MediaTypeNames.Application.Pdf.

Based on the Mime Type, ensure that the correct extension is specified in FileName, for example, "myFile.pdf".

The above is the detailed content of How to Attach Files from a MemoryStream to a MailMessage in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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