HOWTO: Set and Get the a multibyte (Japanese, Chinese, Etc) custom header with CDOSYS

Custom headers in multibyte languages (Japanese, Chinese, etc) will not be encoded
properly when set using CDO alone. They may appear to be correctly set, however
when read back on a recieved message they may be messed-up.

Here is an example of a Japanese header:

I had a case where a customer wanted to read an iso-2022-jp header. This header is custom header and this header is in BodyPart of a message.

On a CDO.Message (obj) which is being sent:

' Append the extended header
    obj.Fields.Append _
        "urn:schemas:mailheader:X-Custom-header",_
        adBSTR, 256, , "???" ' Japanese Character
    obj.Fields.Update

On receiver site, you might get a custom header looking like this:
x-custom-header: =?iso-2022-jp?B?GyRCJUYlOSVIGyhC?=

The the recieved header will not be understandable or convertable to a usable format.

This is by design. X-headers are accessible only through the urn:schemas:mailheader namespace, and we do not decode headers returned through that namespace. It is documented this way in MSDN the reference is:

    https://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_schema_mailheader.asp:

Each field value (with a few exceptions) is stored as US-ASCII characters and is identical to the ASCII string found in the message stream. Non US-ASCII characters are encoded according to the RFC 1522 specification. No conversion is performed when the property value is set or updated. An application that sets the raw message header property must RFC 1522-encode non US-ASCII characters or the header value will be corrupted.

This comes down to the fact that the non-ASCII (multibyte) header text will need to be encoded into a BASE 64 string (to make it RFC 1522 compliant). Encoding of the text will need to be done when the email is being composed and decoding of the text when the header is being read back.

Here are a couple ways to work around this problem:

  1) Use a header field that has an httpmail equivalent to do the decoding:

      set m = createobject("cdo.message")
      m.fields("urn:schemas:mailheader:subject") = theEncodedString
      theDecodedString = m.fields("urn:schemas:httpmail:subject")

      2) Use or write a base64 decoder to extract the 2022-jp text from the header.

          a) With .NET you can use Convert.FromBase64String to convert the header.
 
          b) Use the example from:
              Sample Base 64 Encoding and Decoding - C++
              https://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B191239

             c) Find vb/vbs code by searching the net using the following string:
                  ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

Please read the following for an understanding on base 64 encoding:
XCON: A Description of Base64 MIME Content Transfer Encoding
https://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B323489