Garbled attachment names when sending mail SmtpClient

A phenomenon found in the user's environment, using System.Net.Mail.SmtpClient send mail, when the attachment name contains Chinese and longer length, the final name of the mail attachments will be a mess, write a simple test program:

var mail = new new MailMessage ( " [email protected] " , " [email protected] " ); 
mail.Subject = " test garbled message " ;
 var Atta = new new Attachment ( @ " C: \ test message Chinese garbled 20,150,115 .rar " ); 
mail.Attachments.Add (Atta); 

var SMTP = new new the SmtpClient (); 
smtp.Host = " test.com " ; 
smtp.Credentials = new new the NetworkCredential ( " from " ,"test");
smtp.Send(mail);

 

Use Foxmail receive mail, and view the original e-mail message, a MIME attachment portion is actually found is this:

 

This strange name leads to garbled in the mail client. In other test different machines, some machines is normal, a description of the software environment. Normal mail should look like this:

 

Some research and found that the .Net BUG Framework, see the Microsoft Web site: http: //support.microsoft.com/kb/2402064, when the attachment name more than 41 utf8 byte, would be wrong twice resulting encoded . See patch https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=31723.

 

If the server does not upgrade, you can temporarily modify the program to avoid this BUG, ​​mainly to manually specify the name of the attachment:

var mail = new new MailMessage ( " [email protected] " , " [email protected] " ); 
mail.Subject = " test garbled message " ;
 String File = @ " C: \ test message Chinese garbled 20150115.rar " ;
 var Atta = new new Attachment (File);
 String name = Path.GetFileName (File);
 String Base64 = Convert.ToBase64String (Encoding.UTF8.GetBytes (name)); 
atta.ContentDisposition.FileName = String .Format ( " =? utf-8? B? {0 }? =" , Base64);    // specify the attachment filename 
atta.Name = " p_w_upload " ;            // specify MimePart's Name, do not include Chinese, so it will not be BUG affect 
atta.NameEncoding = Encoding.UTF8; 
mail.Attachments.Add (Atta); 

var SMTP = new new the SmtpClient (); 
smtp.Host = " test.com " ; 
smtp.Credentials = new new the NetworkCredential ( " from " , " Test " ); 
smtp.Send (mail);

 

Mail received at this time is that, draw attention to the red part:

 

Guess you like

Origin www.cnblogs.com/BoyTNT/p/11887281.html