简体   繁体   中英

How can I set the Attachment file encoding for a System.Net.Mail.MailMessage?

I use System.Net.Mail to send out a series of MailMessage with Attachment .

To do this, I fill a MemoryStream with data, using a StreamWriter with Encoding.UTF8 . I then create an Attachment using the MemoryStream . I can set the MIME type for the attachment, the file name, the file name encoding, etc. But what I can't find, is how I explicitly set the attachment encoding...

using (var ms = new MemoryStream())
using (var sw = new StreamWriter(ms, Encoding.UTF8))
{
    //Fill ms with data, using sw

    ms.Position = 0;
    Attachment att = new Attachment(ms, attachmentFileName, MediaTypeNames.Text.Plain);

    MailMessage.Attachments.Add(att);
    SmtpClient.Send(mailMessage);
}

How/where can I state the encoding of the attached file?

I'm no expert in encodings, so if I'm trying to achieve something completely useless and/or impossible, I'd like to hear it too...

I found this static method in Attachment :

public static Attachment CreateAttachmentFromString(
    string content,
    string name,
    Encoding contentEncoding,
    string mediaType
)

So this might be the solution:

Attachment att = Attachment.CreateAttachmentFromString(
    Encoding.UTF8.GetString(ms.ToArray()),
    attachmentFileName,
    Encoding.UTF8,
    System.Net.Mime.MediaTypeNames.Text.Plain);

It forces you to create from a string though, I'd like to see another method which uses just the stream.

您可以将附件的ContentType属性的Charset属性设置为有效值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM