Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET encoding issue of mail attachment (.csv)

Tags:

c#

encoding

I use following code to send a attachment (.csv) with Chinese characters. However, MS excel fails to disply the characters properly, it displays something like "¨å¯¹æ–°ç". Is it because I didn't set some property when sending the mail?

Thanks for any advise.

                byte[] attachBytes = Encoding.UTF8.GetBytes(attachText);
                ms.Write(attachBytes, 0, attachBytes.Length);
                // Set the position to the beginning of the stream.
                ms.Position = 0;
                ContentType ct = new ContentType(MediaTypeNames.Text.Plain);

                Attachment attactment = new Attachment(ms, attachFileName);
                message.Attachments.Add(attactment);
like image 787
Ricky Avatar asked Oct 13 '22 20:10

Ricky


2 Answers

i think you need an extra encoding setup for the mail body object, something like this:

message.BodyEncoding = UTF8
like image 117
Ali Tarhini Avatar answered Nov 15 '22 08:11

Ali Tarhini


Setting the attachments encoding to Encoding.UTF32 could help. Assuming attachText is a string and you only want to add a .csv you could shorten your code by using the Attachment.CreateAttachmentFromString() method:

var attachment = Attachment.CreateAttachmentFromString(attachText,
                                                       "filename.csv",
                                                       Encoding.UTF32,
                                                       "text/csv");
message.Attachments.Add(attachment);
like image 38
Linus Caldwell Avatar answered Nov 15 '22 10:11

Linus Caldwell