You can set the Charset
property of the attachment's ContentType
property to a valid value.
How can I set the Attachment file encoding for a System.Net.Mail.MailMessage?
-
18-07-2023 - |
Frage
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...
Lösung 2
Andere Tipps
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.