简体   繁体   中英

MIME Attachment Names containing Extended Characters Fails

While working on a project that emails files with international filenames, I've come across an unusual issue. if I attach with a US-ASCII filename only, I can get better than 200 characters long without errors.

If I include an extended character, it encodes in UTF-8 and the length before it gets funky is very small (< 40 characters). To define funky.. here's an example filename after it goes bad:

=utf-8BSU5GT1JNw4FUSUNBX0ltcGFjdF9Bc3Nl

it looks like UTF8 encoded string with a UTF-8 decoding instruction or a mime boundary... not sure which.

Has anyone seen this before -- and what are the rules / limitations of filenames -- I tried emailing the file by hand through outlook and it handles it, so I don't think it is a MIME specific limitation.

Sample code:

class Program
{
    private const string DOMAIN = "foobar.com";
    private const string SMTPHOST = "mail." + DOMAIN;
    private const string FROM = "chadwick.posey@" + DOMAIN;
    private const string TO = FROM;

    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage(FROM, TO, "Subject", "Body");

        string path = Path.GetTempPath();
        string name = "AAAAAA_AAAAAAAAAAAA_AAAAAAA_AAAA - IIIIIII CCCCCCCCCC DD IIIIIIÁIIII_20111018_091327.pptx";

        File.WriteAllText(path + "\\" + name, "blah");
        Attachment att = new Attachment(path + "\\" + name, new ContentType("application/vnd.openxmlformats-officedocument.presentationml.presentation"));

        msg.Attachments.Add(att);

        SmtpClient client = new SmtpClient(SMTPHOST, 25);
        client.Send(msg);
    }
}

I've tried (so far) -- setting the encoding for the attachment.NameEncoding to UTF8 and UTF32, neither worked. Setting the ContentDisposition.FileName on the attachment fails because it is not using US-ASCII characters only.

Any suggestions on how to get it to include the full filename with the accent / extended characters in tact?

Thanks Chadwick

There is a hotfix from microsoft that seems to have done the trick for me. Check http://support.microsoft.com/kb/2402064 On that page, there is a download link that will get you what you need. Just install the correct version, depending on your system.

this should work:

Attachment att = new Attachment(@"c:\path to file\somename.txt",    
System.Net.Mime.MediaTypeNames.Application.Octet);

//this itself should work.
att.Name = "история-болезни.doc";  // non-english filename

//if the above line doesn't make it work, try this.
att.Name = System.Web.HttpUtility.UrlEncode(att.Name, System.Text.Encoding.UTF8);

How to set the attatchment file name with chinese characters in C# SmtpClient programming?

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