1

有没有人有能够发送带有附件的电子邮件的示例,其中附件保存为 utf8 编码。我试过了,但是当我在记事本中打开它时,它说编码是ascii。注意:我不想先保存文件。

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

            // Create MailMessage
            MailMessage message = new MailMessage("team@ccccc.co.nz",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);


            }
4

2 回答 2

1

在流的开头添加 UTF-8 的BOM(字节顺序标记) :

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);
于 2012-07-02T23:29:24.537 回答
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;

此外,您应该为附件指定 a TransferEncoding,因为 UTF-8 不是 7 位干净的(许多电子邮件系统仍然需要),例如:

attFile.TransferEncoding = TransferEncoding.QuotedPrintable;  

或者:

attFile.TransferEncoding = TransferEncoding.Base64;  
于 2012-07-02T23:33:07.483 回答