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

时间:2011-03-17 07:45:49

标签: c# email smtp memorystream

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

System.Net.Mail.MailMessage.Attachments.Add(
    new System.Net.Mail.Attachment("file name")); 

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

8 个答案:

答案 0 :(得分:94)

以下是示例代码。

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

基于 Mime类型,您需要在FileName中指定正确的扩展名"myFile.pdf"

答案 1 :(得分:91)

有点迟到 - 但希望对那里的人有用: -

这是一个简化的代码段,用于将内存中的字符串作为电子邮件附件发送(在此特定情况下为CSV文件)。

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)。

答案 2 :(得分:24)

由于我无法在任何地方找到这方面的确认,我测试了如果处理MailMessage和/或Attachment对象会处理加载到它们中的流,正如我预期的那样。

以下测试确实显示,当放置MailMessage时,用于创建附件的所有流也将被处置。因此,只要您处置MailMessage,创建它的流就不需要处理了。

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

答案 3 :(得分:17)

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

  Could not find a version that satisfies the requirement libsasl2-dev (from versions: ) No matching distribution found for libsasl2-dev

答案 4 :(得分:12)

如果你所做的只是附加一个字符串,你可以只用两行:

mail.Attachments.Add(Attachment.CreateAttachmentFromString("1,2,3", "text/csv");
mail.Attachments.Last().ContentDisposition.FileName = "filename.csv";

我无法使用StreamWriter使用我们的邮件服务器工作 我想也许是因为使用StreamWriter你会丢失很多文件属性信息,也许我们的服务器不喜欢丢失的内容。
使用Attachment.CreateAttachmentFromString(),它创建了我需要的一切并且效果很好!

否则,我建议将你的文件放在内存中并使用MemoryStream(byte [])打开它,并一起跳过StreamWriter。

答案 5 :(得分:2)

我登陆了这个问题,因为我需要附加一个我通过代码生成的Excel文件,并以MemoryStream的形式提供。我可以将它附加到邮件消息,但它被发送为64Bytes文件,而不是它的意思是~6KB。所以,对我有用的解决方案就是:

MailMessage mailMessage = new MailMessage();
Attachment attachment = new Attachment(myMemorySteam, new ContentType(MediaTypeNames.Application.Octet));

attachment.ContentDisposition.FileName = "myFile.xlsx";
attachment.ContentDisposition.Size = attachment.Length;

mailMessage.Attachments.Add(attachment);

设置attachment.ContentDisposition.Size的值,让我发送附件大小正确的邮件。

答案 6 :(得分:2)

使用OTHER OPEN memorystream:

lauch pdf的示例,并在MVC4 C#Controller

中发送pdf
        public void ToPdf(string uco, int idAudit)
    {
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("content-disposition", "attachment;filename= Document.pdf");
        Response.Buffer = true;
        Response.Clear();

        //get the memorystream pdf
        var bytes = new MisAuditoriasLogic().ToPdf(uco, idAudit).ToArray();

        Response.OutputStream.Write(bytes, 0, bytes.Length);
        Response.OutputStream.Flush();

    }


    public ActionResult ToMail(string uco, string filter, int? page, int idAudit, int? full) 
    {
        //get the memorystream pdf
        var bytes = new MisAuditoriasLogic().ToPdf(uco, idAudit).ToArray();

        using (var stream = new MemoryStream(bytes))
        using (var mailClient = new SmtpClient("**YOUR SERVER**", 25))
        using (var message = new MailMessage("**SENDER**", "**RECEIVER**", "Just testing", "See attachment..."))
        {

            stream.Position = 0;

            Attachment attach = new Attachment(stream, new System.Net.Mime.ContentType("application/pdf"));
            attach.ContentDisposition.FileName = "test.pdf";

            message.Attachments.Add(attach);

            mailClient.Send(message);
        }

        ViewBag.errMsg = "Documento enviado.";

        return Index(uco, filter, page, idAudit, full);
    }

答案 7 :(得分:-6)

我认为此代码可以帮助您:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {

  }

  protected void btnSubmit_Click(object sender, EventArgs e)
  {
    try
    {
      MailAddress SendFrom = new MailAddress(txtFrom.Text);
      MailAddress SendTo = new MailAddress(txtTo.Text);

      MailMessage MyMessage = new MailMessage(SendFrom, SendTo);

      MyMessage.Subject = txtSubject.Text;
      MyMessage.Body = txtBody.Text;

      Attachment attachFile = new Attachment(txtAttachmentPath.Text);
      MyMessage.Attachments.Add(attachFile);

      SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
      emailClient.Send(MyMessage);

      litStatus.Text = "Message Sent";
    }
    catch (Exception ex)
    {
      litStatus.Text = ex.ToString();
    }
  }
}