2012-07-02 83 views
1

有沒有人有一個例子,能夠發送附件保存爲utf8編碼的附件的電子郵件。我試過,但是當我在記事本中打開它說編碼是ascii。注意:我不想先保存文件。電子郵件中的附件以UTF-8編碼保存

// Init the smtp client and set the network credentials 
      SmtpClient smtpClient = new SmtpClient(); 
      smtpClient.Host = getParameters("MailBoxHost"); 

      // Create MailMessage 
      MailMessage message = new MailMessage("[email protected]",toAddress,subject, body); 

      using (MemoryStream memoryStream = new MemoryStream()) 
      { 
       byte[] contentAsBytes = Encoding.UTF8.GetBytes(attachment); 
       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.Name = attachementname; 
       contentType.CharSet = "UTF-8"; 

       System.Text.Encoding inputEnc = System.Text.Encoding.UTF8; 

       Attachment attFile = new Attachment(memoryStream, contentType); 

       // Add the attachment 
       message.Attachments.Add(attFile); 

       // Send Mail via SmtpClient 
       smtpClient.Send(message); 


      } 

回答

1

爲UTF-8添加BOM (byte order mark)在流的開頭:

0xEF,0xBB,0xBF 

代碼:

byte[] bom = { 0xEF, 0xBB, 0xBF }; 
memoryStream.Write(bom, 0, bom.Length); 

byte[] contentAsBytes = Encoding.UTF8.GetBytes(attachment); 
memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length); 
1

假設你的附件是文本,則ContentType類的默認構造函數會將附件的Content-Type標題設置爲application/octet-stream,但它需要設置爲text/plain,例如:

ContentType contentType = new ContentType(MediaTypeNames.Text.Plain); 

或者:

ContentType contentType = new ContentType(); 
contentType.MediaType = MediaTypeNames.Text.Plain; 

此外,您應該指定附件一TransferEncoding,爲UTF-8是不是7位乾淨(其中許多電子郵件系統仍然需要),例如:

attFile.TransferEncoding = TransferEncoding.QuotedPrintable; 

或者:

attFile.TransferEncoding = TransferEncoding.Base64;