Skip to content

Commit

Permalink
Support UTF8 in EML files #662
Browse files Browse the repository at this point in the history
  • Loading branch information
the-djmaze committed Nov 14, 2022
1 parent 31aaf80 commit bc5194a
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions dev/Mime/Parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
const
// RFC2045
QPDecodeIn = /=([0-9A-F]{2})/g,
QPDecodeOut = (...args) => String.fromCharCode(parseInt(args[1], 16));
QPDecodeOut = (...args) => String.fromCharCode(parseInt(args[1], 16)),

utf8To16 = data => new TextDecoder().decode(Uint8Array.from(data, c => c.charCodeAt(0)));

export function ParseMime(text)
{
Expand Down Expand Up @@ -43,11 +45,12 @@ export function ParseMime(text)
// charset = this.header('content-type')?.params.charset,
encoding = this.headerValue('content-transfer-encoding');
if ('quoted-printable' == encoding) {
body = body.replace(/=\r?\n/g, '').replace(QPDecodeIn, QPDecodeOut);
body = utf8To16(body.replace(/=\r?\n/g, '').replace(QPDecodeIn, QPDecodeOut));
} else if ('base64' == encoding) {
body = atob(body.replace(/\r?\n/g, ''));
body = utf8To16(atob(body.replace(/\r?\n/g, '')));
}
/*
// TODO: convert charsets other then utf8
try {
// https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API/Encodings
return new TextDecoder(charset).decode(Uint8Array.from(body, c => c.charCodeAt(0)));
Expand Down Expand Up @@ -111,8 +114,18 @@ export function ParseMime(text)
[...header.matchAll(/;\s*([^;=]+)=\s*"?([^;"]+)"?/g)].forEach(param =>
params[param[1].trim().toLowerCase()] = param[2].trim()
);
// encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
match[2] = match[2].trim().replace(/=\?([^?]+)\?(B|Q)\?(.+?)\?=/g, (m, charset, encoding, text) => {
m = decodeURIComponent(
'B' == encoding ? escape(atob(text))
// else 'Q'
: text.replace(/=([A-Z0-9]{2})/, '%$1')
);
// TODO: convert when charset != utf-8
return m;
});
headers[match[1].trim().toLowerCase()] = {
value: match[2].trim(),
value: match[2],
params: params
};
}
Expand Down

0 comments on commit bc5194a

Please sign in to comment.