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

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

DDD
Release: 2025-01-02 15:18:38
Original
443 people have browsed it

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

Attaching a File from MemoryStream to a MailMessage in C#

In this article, we'll address the issue of attaching a file from a MemoryStream to a MailMessage in C#.

Issue:

The reader is currently storing files on disk using FileStream and then adding them as attachments using System.Net.Mail.MailMessage.Attachments.Add. However, they wish to avoid storing files on disk and instead work with MemoryStream.

Solution:

To achieve this, we can utilize the following approach:

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

Additional Notes:

  • It is important to specify the MimeType when creating the ContentType.
  • You should specify the correct extension in FileName based on the MimeType, e.g., "myFile.pdf" for PDFs.

The above is the detailed content of How to Attach a File from a MemoryStream to a MailMessage 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template