Attach a file from MemoryStream to a MailMessage in C#(将文件从 MemoryStream 附加到 C# 中的 MailMessage)
问题描述
我正在编写一个将文件附加到电子邮件的程序.目前我正在使用 FileStream
将文件保存到磁盘中,然后我使用
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"));
我不想将文件存储在磁盘中,我想将文件存储在内存中,然后从内存流中将其传递给 Attachment
.
I do not want to store file in disk, I want to store file in memory and from memory stream pass this to Attachment
.
推荐答案
这里是示例代码.
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();
编辑 1
您可以通过 System.Net.Mime.MimeTypeNames 指定其他文件类型,例如 System.Net.Mime.MediaTypeNames.Application.Pdf
You can specify other file types by System.Net.Mime.MimeTypeNames like System.Net.Mime.MediaTypeNames.Application.Pdf
根据 Mime 类型,您需要在 FileName 中指定正确的扩展名,例如 "myFile.pdf"
Based on Mime Type you need to specify correct extension in FileName for instance "myFile.pdf"
这篇关于将文件从 MemoryStream 附加到 C# 中的 MailMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将文件从 MemoryStream 附加到 C# 中的 MailMessage


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01