package
Encode and decode quoted printable and base64 strings
npm install libmimeGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
libmime provides useful MIME related functions. For Quoted-Printable and Base64 encoding and decoding see libqp and libbase64.
npm install libmimelibmime is written in TypeScript and ships both an ES module and a CommonJS build, each with type declarations. Node.js 20 or newer is required.
// ES modules
import libmime from 'libmime';
// CommonJS
const libmime = require('libmime');The default export is a shared Libmime instance. The class itself is available as Libmime for creating instances of your own:
import { Libmime } from 'libmime';
// or: const { Libmime } = require('libmime');
const mime = new Libmime();The helper modules can be loaded directly as well, for example libmime/lib/charset (encode, decode, convert, normalizeCharset, createDecodeStream, DecodeStream) and libmime/lib/mimetypes (list, extensions).
The bundled declarations replace @types/libmime, which can be removed. The type names it used keep working: libmime.StructuredHeader and libmime.MimeWordEncoding are available through the default export, next to the other public types (ParsedHeaderValue, StructuredHeaderValue, HeaderParam, HeaderLine, HeaderObject), which can also be imported by name:
import libmime, { type ParsedHeaderValue } from 'libmime';
const parsed: ParsedHeaderValue = libmime.parseHeaderValue('text/plain; charset=utf-8');Encodes a string into mime encoded word format.
libmime.encodeWord(str [, mimeWordEncoding[, maxLength]]) → StringExample
libmime.encodeWord('See on õhin test', 'Q');Becomes with UTF-8 and Quoted-printable encoding
=?UTF-8?Q?See_on_=C3=B5hin_test?=Encodes non ascii sequences in a string to mime words.
libmime.encodeWords(str [, mimeWordEncoding[, maxLength[, fromCharset]]]) → Stringstr (defaults to 'UTF-8')Decodes a string that might include one or several mime words. If no mime words are found from the string, the original string is returned
libmime.decodeWords(str) → StringFolds a long line according to the RFC 5322. Mostly needed for folding header lines.
libmime.foldLines(str [, lineLength[, afterSpace]]) → StringExample
libmime.foldLines('Content-Type: multipart/alternative; boundary="----zzzz----"', 40)results in
Content-Type: multipart/alternative;
boundary="----zzzz----"Adds soft line breaks to content marked with format=flowed options to ensure that no line in the message is never longer than lineLength.
libmime.encodeFlowed(str [, lineLength]) → StringUnwraps a plaintext string in format=flowed wrapping.
libmime.decodeFlowed(str [, delSp]) → StringUnfolds a header line and splits it to key and value pair. The return value is in the form of {key: 'subject', value: 'test'}. The value is not mime word decoded, you need to do your own decoding based on the rules for the specific header key.
libmime.decodeHeader(headerLine) → ObjectParses a block of header lines. Does not decode mime words as every header might have its own rules (eg. formatted email addresses and such).
Return value is an object of headers, where header keys are object keys and values are arrays.
libmime.decodeHeaders(headers[, options]) → Objecttrue, headers named like an Object.prototype member (__proto__, constructor) are left out. By default they are kept as own properties of the resultParses a header value with key=value arguments into a structured object. Useful when dealing with
content-type and such. Continuation encoded params are joined into mime encoded words.
parseHeaderValue(valueString[, options]) → Objecttrue, RFC 822 comments outside quoted strings are dropped, so boundary=b (comment) gives the boundary b. A parenthesis right behind the = of a parameter or behind a token of its value continues the token, filename=Invoice(1).pdf keeps its name and boundary=(c)b names the boundary (c)b, as both do for Python and postal-mime. A comment that never closes runs to the end of the value, unless a parameter follows it, in which case it is content and the parameter survives. Use it for the MIME headers (Content-Type, Content-Disposition). By default comments are kept, since a header such as Authentication-Results carries information in themA parameter value is a token or a quoted string, so what follows a closed quoted string up to the next ; is
dropped (boundary="b"c gives b), and a parameter that occurs more than once keeps its first value, both as Python and postal-mime read them. An RFC 2231
continuation overrides the plain parameter of the same name in either order, libmime's own rule after RFC 6266
section 4.3.
Example
parseHeaderValue('text/plain; CHARSET="UTF-8"');Outputs
{
"value": "text/plain",
"params": {
"charset": "UTF-8"
}
}Joins structured header value together as 'value; param1=value1; param2=value2'
buildHeaderValue(structuredHeader) → StringparseHeaderValuefilename argument is encoded with continuation encoding if needed
Encodes and splits a header param value according to RFC2231 Parameter Value Continuations.
libmime.buildHeaderParam(key, str [, maxLength[, fromCharset]]) → Arrayfilename)str when it is a Buffer (defaults to 'UTF-8')The method returns an array of encoded parts with the following structure: [{key:'...', value: '...'}]
Example
libmime.buildHeaderParam('filename', 'filename õäöü.txt', 20);
→
[ { key: 'filename*0*', value: 'utf-8\'\'filename%20' },
{ key: 'filename*1*', value: '%C3%B5%C3%A4%C3%B6' },
{ key: 'filename*2*', value: '%C3%BC.txt' } ]This can be combined into a properly formatted header:
Content-disposition: attachment; filename*0*=utf-8''filename%20
filename*1*=%C3%B5%C3%A4%C3%B6; filename*2*=%C3%BC.txtResolves a charset name to its canonical form, eg. win-1257 becomes windows-1257. Unknown names are returned uppercased.
libmime.normalizeCharset(charset) → StringCreates a Transform stream that decodes bytes in a charset into UTF-8 Buffers, for example a message body. The output is what decoding the whole input at once gives, however it is split into chunks. The charset name is resolved the same way as for encoded words, the Japanese charsets iconv-lite does not support (ISO-2022-JP and friends) are decoded with encoding-japanese, which is not incremental, so such input is collected until the stream ends. The double byte charsets (Shift_JIS, GBK, GB18030, Big5, EUC-KR, EUC-JP) are decoded up to the last byte below 0x30 (a space, a line break, most ASCII punctuation) of what has arrived, so input without any such byte is held until the stream ends as well.
libmime.createDecodeStream(charset) → DecodeStreamThe stream has two extra properties:
false when the charset is unknown or refused (UTF-7, which could smuggle markup past filters, and the base64 and hex transfer encodings). The input is then decoded as UTF-8 regardless, invalid bytes replaced with U+FFFD, the same fallback encoded words get. Check it before piping when the bytes must not be relabelled as UTF-8, for example to keep the original part as it isconst stream = libmime.createDecodeStream('iso-8859-1');
if (stream.supported) {
body.pipe(stream).pipe(output);
}Returns file extension for a content type string. If no suitable extensions are found, 'bin' is used as the default extension.
libmime.detectExtension(mimeType) → StringExample
libmime.detectExtension('image/jpeg') // returns 'jpeg'Returns content type for a file extension. If no suitable content types are found, 'application/octet-stream' is used as the default content type
libmime.detectMimeType(extension) → StringExample
libmime.detectMimeType('logo.jpg') // returns 'image/jpeg'MIT
Estimated unpacked size across 6 packages.
1.2 MB
Includes dependencies.
4 direct dependencies.