# (chibi mime)

A library to parse MIME headers and bodies into SXML.

#### `(assq-ref ls key [default])`

Returns the `cdr` of the cell in `ls` whose `car` is `eq?` to `key`, or `default` if not found. Useful for retrieving values associated with MIME headers.

#### `(mime-type-from-extension ext)`

## RFC2822 Headers

#### `(mime-header-fold kons knil [source [limit [kons-from]]])`

Performs a fold operation on the MIME headers of source which can be either a string or port, and defaults to current-input-port. `kons` is called on the three values: `(kons header value accumulator)` where accumulator begins with `knil`. Neither the header nor the value are modified, except wrapped lines are handled for the value.

The optional procedure `kons-from` is a procedure to be called when the first line of the headers is an "From <address> <date>" line, to enable this procedure to be used as-is on mbox files and the like. It defaults to `kons`, and if such a line is found the fold will begin with `(kons-from '%from <address> (kons-from '%date <date> knil))`.

The optional `limit` gives a limit on the number of headers to read.

#### `(mime-headers->list [source])`

Return an alist of the MIME headers from source with headers all downcased.

#### `(mime-parse-content-type str)`

Parses `str` as a Content-Type style-value returning the list `(type (attr . val) ...)`.

    (mime-parse-content-type "text/html; CHARSET=UTF-8; filename=index.html")

`=> (text/html (charset . "UTF-8") (filename . "index.html"))`

#### `(mime-decode-header str)`

Replace all occurrences of RFC1522 =?ENC?...?= escapes in `str` with the appropriate decoded and charset converted value.

#### `(mime-write-headers headers out)`

Write out an alist of headers in mime format.

## RFC2045 MIME Encoding

#### `(mime-message-fold src kons knil [down up headers])`

Performs a tree fold operation on the given string or port `src` as a MIME body corresponding to the headers give in `headers`. If `headers` are false or not provided they are first read from `src`.

`kons` is called on the successive values:

    (kons parent-headers part-headers part-body accumulator)

where `part-headers` are the headers for the given MIME part (the original headers for single-part MIME), `part-body` is the appropriately decoded and charset-converted body of the message, and the `accumulator` begins with `knil`.

If a multipart body is found, then a tree fold is performed, calling `down` once to get a new accumulator to pass to `kons`, and `up` on the result when returning. Their signatures are:

    (down headers seed)

    (up headers parent-seed seed)

The default `down` simply returns null, and the default `up` wraps the seed in the following sxml:

     ((mime (@ headers ...)
        seed ...)
      parent-seed ...)

#### `(mime-message->sxml [src [headers]])`

Parse the given source as a MIME message and return the result as an SXML object of the form: `(mime (@ (header . value) ...) parts ...)`.