首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将文件从MemoryStream附加到C#中的MailMessage

将文件从MemoryStream附加到C#中的MailMessage
EN

Stack Overflow用户
提问于 2011-03-17 15:45:49
回答 7查看 189.8K关注 0票数 124

我正在编写一个程序,以附加文件到电子邮件。目前我正在使用FileStream将文件保存到磁盘中,然后使用

代码语言:javascript
复制
System.Net.Mail.MailMessage.Attachments.Add(
    new System.Net.Mail.Attachment("file name")); 

我不想将文件存储在磁盘中,我想将文件存储在内存中,并从内存流中将此文件传递给Attachment

EN

回答 7

Stack Overflow用户

发布于 2013-02-13 03:04:37

入门有点晚-但希望对外面的人仍然有用:

下面是一个简化的代码片段,用于将内存中的字符串作为电子邮件附件(在本例中为CSV文件)发送。

代码语言:javascript
复制
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))    // using UTF-8 encoding by default
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("me@example.com", "you@example.com", "Just testing", "See attachment..."))
{
    writer.WriteLine("Comma,Seperated,Values,...");
    writer.Flush();
    stream.Position = 0;     // read from the start of what was written

    message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));

    mailClient.Send(message);
}

在消息发送之前,不应该释放StreamWriter和底层流(以避免ObjectDisposedException: Cannot access a closed Stream)。

票数 100
EN

Stack Overflow用户

发布于 2011-10-19 06:11:40

因为我在任何地方都找不到这一点的确认,所以我测试了MailMessage和/或附件对象的处置是否会像我预期的那样处置加载到它们中的流。

下面的测试表明,当MailMessage被释放时,用于创建附件的所有流也将被释放。因此,只要您处理了MailMessage,创建它的流就不需要再处理了。

代码语言:javascript
复制
MailMessage mail = new MailMessage();
//Create a MemoryStream from a file for this test
MemoryStream ms = new MemoryStream(File.ReadAllBytes(@"C:\temp\test.gif"));

mail.Attachments.Add(new System.Net.Mail.Attachment(ms, "test.gif"));
if (mail.Attachments[0].ContentStream == ms) Console.WriteLine("Streams are referencing the same resource");
Console.WriteLine("Stream length: " + mail.Attachments[0].ContentStream.Length);

//Dispose the mail as you should after sending the email
mail.Dispose();
//--Or you can dispose the attachment itself
//mm.Attachments[0].Dispose();

Console.WriteLine("This will throw a 'Cannot access a closed Stream.' exception: " + ms.Length);
票数 31
EN

Stack Overflow用户

发布于 2015-10-21 22:25:46

如果你真的想要添加一个.pdf,我发现有必要将内存流的位置设置为零。

代码语言:javascript
复制
var memStream = new MemoryStream(yourPdfByteArray);
memStream.Position = 0;
var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
var reportAttachment = new Attachment(memStream, contentType);
reportAttachment.ContentDisposition.FileName = "yourFileName.pdf";
mailMessage.Attachments.Add(reportAttachment);
票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5336239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档