2015-09-04 44 views
0

如果找到附件,我将获取带有附件的电子邮件,然后将该电子邮件转发给某个用户。我用下面的代码来做到这一点。当我使用下面的代码时,它会发送带有附件 的电子邮件,但附件没有内容(空白附件)。你能告诉我我错在哪里吗?如何从附件中编写附件?

public bool AddAttachment(System.IO.Stream sm, string fileName) 
    { 
     try 
     { 
      System.Net.Mail.Attachment atch = new System.Net.Mail.Attachment(sm, fileName); 
      msg.Attachments.Add(atch); 
      return true; 
     } 
     catch (Exception ex) 
     { 
      TraceService(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace); 
     } 
     return false; 
    } 

ObjMail.MsgData = strBuilder.ToString(); 
      for (int i = 0; i < sMail.Attachments.Length; i++) 
      { 
       if (!string.IsNullOrEmpty(sMail.Attachments[i].Name)) 
       { 
        if (!sMail.Attachments[i].Name.Contains(".dat")) 
        { 
         System.IO.MemoryStream ms = new System.IO.MemoryStream(); 
         System.IO.StreamWriter writer = new System.IO.StreamWriter(ms); 
         var sr = new StreamReader(ms); 
         writer.Write(sMail.Attachments[i]); 

         ObjMail.AddAttachment(ms, sMail.Attachments[i].Name); 
        } 
       } 
      } 
ObjMail.SendMail(); 
+0

你在做什么代码System.IO.MemoryStream ms = new Syst em.IO.MemoryStream(); System.IO.StreamWriter writer = new System.IO.StreamWriter(ms); var sr = new StreamReader(ms); writer.Write(sMail.Attachments [i]);? –

+0

@ KirillBestemyanov-如果在电子邮件中发现附件,我在内存流中编写附件并发送一封包含该附件的新电子邮件 – skiskd

+0

您的代码不会将附件写入内存流。此外,您的代码不会编译,因为您传递给Attachment类型的方法Write变量,而不是字符串或char数组。正如我在回答中所说的,只需使用CopyTo方法而不是Streamwriter和Stream Reader –

回答

0

要安装使用下面的代码,我使用的示例附上JPG图片

Attachment attach = new Attachment(id + ".jpg"); 
attach.Name = "WhateverName.jpg"; 
mail.Attachments.Add(attach); 
0

试试这个:

if (!string.IsNullOrEmpty(sMail.Attachments[i].Name)) 
       { 
        if (!sMail.Attachments[i].Name.Contains(".dat")) 
        { 
         System.IO.MemoryStream ms = new System.IO.MemoryStream(); 
         sMail.Attachments[i].ContentStream.CopyTo(ms); 

         ObjMail.AddAttachment(ms, sMail.Attachments[i].Name); 
        } 
       } 

或者,你可以使用简单:

if (!string.IsNullOrEmpty(sMail.Attachments[i].Name)) 
        { 
         if (!sMail.Attachments[i].Name.Contains(".dat")) 
         { 
          ObjMail.Add(sMail.Attachments[i]); 
         } 
        } 
ObjMail.SendMail();