在ASP.NET中附加来自Stream的Excel文件?

时间:2012-05-11 14:35:20

标签: asp.net email stream

我有一个excel文档。我想将它作为附件从邮件发送。

它用附件发送邮件但我无法正确打开excel文件

这是我的代码:

public static string EPostaGonder(...,Stream AttachmentStream,string AttachmentFileName)
    {
      .
      .
      .
       SmtpClient mailClient = new SmtpClient(Host, Port);
       mailClient.EnableSsl = true;
       NetworkCredential cred = new NetworkCredential(KullaniciAdi, Sifre);
       mailClient.Credentials = cred;

       MailMessage ePosta = new MailMessage();
       ePosta.IsBodyHtml = true;
       ePosta.From = new MailAddress(Kimden, Isim);
       foreach (string Kime_ in Kime.Split(';'))
       {
         if (Kime_.Trim() != "")
            ePosta.To.Add(Kime_.Trim());


       ePosta.Subject = Konu;
       ePosta.Body = Mesaj.Replace("\n","<br/>");
       if (Cc != "")
         ePosta.CC.Add(Cc);

       if (AttachmentStream != null)
          {
             AttachmentStream .Seek(0, SeekOrigin.Begin);                 
             ePosta.Attachments.Add(
                      new Attachment(AttachmentStream, AttachmentFileName + ".xlsx"));
          }


        try
        {
           //mailClient.SendAsync(ePosta, (object)ePosta);
           mailClient.Send(ePosta);

             return "Done";
        }
         catch (SmtpException SmtpException_)
         {
             return SmtpException_.Message;
         }

  }

2 个答案:

答案 0 :(得分:1)

使用以下代码在邮件中添加附件。只需将文件路径传递给Attachment构造函数。

Attachment attachment = new Attachment(file);
ePosta.Attachments.Add(attachment);

从流中添加附件

ePosta.Attachments.Add( new Attachment( AttachmentStream, filename, "application/msexcel" ));

答案 1 :(得分:0)

尝试类似

的内容
var attach = new MailAttachment(Server.MapPath(strFileName));
ePosta.Attachments.Add(attach);

查看有关ASP.NET email with multiple attachments

的这篇文章