Search code examples
c#mailkit

Get raw file name from attachments file Mailkit


This is log from fetch:

var items = client.Inbox.Fetch(new[] { uid }, MessageSummaryItems.BodyStructure | MessageSummaryItems.UniqueId);
foreach (var item in items)
{
    var attachments = item.Attachments.OfType<BodyPartBasic>();
    foreach (var attachment in attachments)
    {
        Console.WriteLine(attachment.FileName); // return "$B!Z(BFIlE$B![(B.pdf"
    }
}

S: * 25 FETCH (UID 24458 BODYSTRUCTURE ((("text" "plain" ("charset" "iso-2022-jp") NIL NIL "quoted-printable" 143 7 NIL NIL NIL NIL)("text" "html" ("charset" "iso-2022-jp") NIL NIL "quoted-printable" 1108 28 NIL NIL NIL NIL) "alternative" ("boundary" "----=_NextPart_001_0025_01DB2399.BBE7F130") NIL NIL NIL)("application" "pdf" ("name" "=?iso-2022-jp?B?GyRCIVsbKEJGSUxFGyRCIVsbKEIucGRm?=") NIL NIL "base64" 121386 NIL ("attachment" ("filename" "=?iso-2022-jp?B?GyRCIVsbKEJGSUxFGyRCIVsbKEIucGRm?=")) NIL NIL) "mixed" ("boundary" "----=_NextPart_000_0024_01DB2399.BBE7F130") NIL NIL NIL)) S: A00000005 OK Fetch completed (0.001 + 0.000 secs).

I try to get file name from attachments ($B!Z(BFIlE$B![(B.pdf) but it's not the same as original name (【FILE】.pdf)

How can I get correct name file?


Solution

  • When I test this in my own copy of MailKit locally, I get the filename as "】FILE】.pdf" which is not quite what you said you expected to get, but it's closer than what you got on your machine.

    Based on the value you got and what I got locally, it leads me to believe that you did not initialize your .NET character encodings correctly in your app before decoding strings in MimeKit/MailKit.

    Unfortunately, .NET Core (and .NET Framework in some ASP.NET environments) does not come bundled with support for all of the necessary character encodings that are needed. They generally only support Unicode, UTF-8, ASCII and perhaps iso-8859-1 or Windows-CP1251. Notice that iso-2022-jp is not among the default supported character encodings.

    To add support for other character encodings, you need to add a NuGet package dependency on System.Text.Encoding.CodePages and then you need to initialize that package in your program startup code by calling:

    System.Text.Encoding.RegisterProvider (System.Text.CodePagesEncodingProvider.Instance);