2015-09-04 43 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();