2011-10-30 40 views
0

我試圖將XElement附加到我發送的SMTP郵件。如何將XElement附加到SMTP郵件中作爲C#中的附件

我的代碼如下所示:

XElement xmlMsg = new XElement("Test",new XElement("TestSon", "DummyValue"),new XElement("TestSon2","DummyValue")); 
using (MemoryStream memoryStream = new MemoryStream()) 
    { 
     byte[] contentAsBytes = Encoding.Default.GetBytes(xmlMsg.ToString()); 
     memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length); 
     // Set the position to the beginning of the stream. 

     memoryStream.Seek(0, SeekOrigin.Begin); 

     // Create attachment 

     ContentType contentType = new ContentType(); 
     contentType.MediaType = MediaTypeNames.Text.Plain; 
     contentType.Name = "Conversation.xml"; 
     Attachment attachment = new Attachment(memoryStream, contentType); 
     mail.Attachments.Add(attachment); 
     Server.Send(mail); 
    } 

但是,我接收到電子郵件,並在最後剪輯的XML文件,而最後2個字符...

我失去了一些東西?

感謝

回答

0

什麼編碼Encoding.Default您的系統上?

如果是UTF-16,我預計這兩個字節是一個BOM(它由於某種原因)沒有包含在字節數中。

建議:

  • xmlMsg.ToString()到一個局部變量,並檢查它在調試器。
  • 查看memoryStream中的字節
  • 查看原始郵件中的電子郵件內容,可能會複製未編碼的附件,以便手動解碼爲二進制文件。

即,儘可能少的自動重新解釋(例如通過XML查看器)檢查每一步。

相關問題