HOW-TO

How to decode adjacent RFC 2047 encoded words in Node.js

Published · Updated

Code

js
'use strict';

// =?charset*lang?B|Q?payload?=
const ENCODED_WORD = /=\?([^?\s*]+)(?:\*[^?\s]*)?\?([bBqQ])\?([^?\s]*)\?=/g;

function wordToBytes(encoding, text) {
  if (encoding.toUpperCase() === 'B') return Buffer.from(text, 'base64');
  const bytes = [];
  for (let i = 0; i < text.length; i++) {
    const hex = text.slice(i + 1, i + 3);
    if (text[i] === '=' && /^[0-9a-fA-F]{2}$/.test(hex)) {
      bytes.push(parseInt(hex, 16));
      i += 2;
    } else {
      bytes.push(text[i] === '_' ? 0x20 : text.charCodeAt(i) & 0xff);
    }
  }
  return Buffer.from(bytes);
}

function bytesToText(charset, chunks) {
  const bytes = Buffer.concat(chunks);
  try {
    return new TextDecoder(charset).decode(bytes);
  } catch {
    return bytes.toString('latin1'); // unknown charset label: keep it readable
  }
}

function decodeHeader(raw) {
  const value = raw.replace(/\r?\n(?=[ \t])/g, ''); // unfold folded header lines
  let out = '';
  let last = 0;
  let run = null; // { charset, chunks } for the current run of adjacent words
  const flush = () => {
    if (run) out += bytesToText(run.charset, run.chunks);
    run = null;
  };

  for (const m of value.matchAll(ENCODED_WORD)) {
    const gap = value.slice(last, m.index);
    const charset = m[1].toLowerCase();
    const adjacent = run !== null && /^\s*$/.test(gap);
    if (!adjacent) {
      flush();
      out += gap; // real text between words: keep it, spaces included
    } else if (run.charset !== charset) {
      flush(); // gap is dropped, but bytes of different charsets are not mixed
    }
    if (!run) run = { charset, chunks: [] };
    run.chunks.push(wordToBytes(m[2], m[3]));
    last = m.index + m[0].length;
  }
  flush();
  return out + value.slice(last);
}

if (typeof module !== 'undefined') module.exports = { decodeHeader };

console.log(decodeHeader('=?UTF-8?Q?Developme?= =?UTF-8?Q?nt?=')); // Development

Why it happens

An encoded word may be at most 75 characters long, so mail clients cut long subjects into several encoded words. They put a space or a line break between them. RFC 2047 says that this whitespace is only a separator and is not part of the text.

A decoder that replaces each encoded word on its own keeps the separator, so you get Developme nt. Some senders also cut in the middle of a multi-byte character. Decoding each word separately then gives broken characters, even when the space is removed.

Steps

  1. Unfold the header by removing line breaks that are followed by a space or tab.
  2. Find every encoded word and read its charset, encoding (B or Q) and payload.
  3. Convert each payload to raw bytes: Base64 for B, or =XX and _ handling for Q.
  4. Look at the text between the previous word and this one. If it is only whitespace, drop it.
  5. If the charset is the same as the previous word, add the bytes to the same run.
  6. When a run ends, decode all its bytes to text once with TextDecoder.
  7. Keep any normal text between words unchanged, including its spaces.

Pitfalls

  • TextDecoder follows the WHATWG charset table. The label iso-8859-1 is decoded as windows-1252, which differs for bytes 0x80–0x9F.
  • Legacy charsets such as shift_jis or windows-1258 need a Node build with full ICU. Official Node builds have it; some custom builds do not.
  • The code also joins words with no whitespace between them. The RFC does not allow that form, but real mail contains it.
  • This decodes a header value for display. Do not decode an address header before you parse the addresses, because a decoded name may contain commas or angle brackets.

Seen on: Own project ·

Related service: Python automation and data collection