如何从MemoryStream的文件附加到一个在MAILMESSAGE C# [英] How to attach a file from MemoryStream to a MailMessage in c#

查看:2178
本文介绍了如何从MemoryStream的文件附加到一个在MAILMESSAGE C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个程序文件附加到电子邮件。目前我使用的文件保存的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")); 

但我不希望存储文件的磁盘,我想存储文件在内存中,并从内存流通过这附件

推荐答案

下面是示例code。

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();

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.MediaTypeNames.Application.Pdf

根据 Mime类型您需要在文件名指定正确的扩展名,例如myFile.pdf

Based on Mime Type you need to specify correct extension in FileName for instance "myFile.pdf"

这篇关于如何从MemoryStream的文件附加到一个在MAILMESSAGE C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆