Search code examples
c#emailmimeimaplib

vietnamese email subject encoding?


Subject: Re:
 =?UTF-8?Q?Th=E1=BA=A7y_g=E1=BB=ADi_b=C3=A0i_t=E1=BA=ADp_cho_em_v=E1=BB?=
 =?UTF-8?Q?=9Bi.?=

I received an email with this subject header. How should it be decoded?


Solution

  • It's a MIME encoded-word. The syntax is =?charset?transfer-encoding?encoded-data?=. Transfer encoding is Base64 or Quoted-printable.

    To decode it:

    1. Split the encoded word into its 3 parts.
    2. Decode the data (3rd part) into byte[] according to its transfer encoding (2nd part). In this case, the Q encoding is used, so replace the =xx sequences with the corresponding octets. This gives you the two byte arrays [84, 104, 225, 186, 167, 121, 95, 103, 225, 187, 173, 105, 95, 98, 195, 160, 105, 95, 116, 225, 186, 173, 112, 95, 99, 104, 111, 95, 101, 109, 95, 118, 225, 187] and [155, 105, 46].
    3. Decode these byte arrays according to the specified encoding.

    In this particular example, both of the encoded-words are invalid: The first one is missing a trail byte of a 3-byte UTF-8 character, and the second one starts with a trail byte. But combined, they're valid UTF-8, and decode to the string Thầy_gửi_bài_tập_cho_em_với. (which Google Translates to "Teacher sent me to exercise.")