mailmate 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 88d6dabd89e0d5e37026235c1e97fff082e6f1e2a81c6fe372ba224dacacbe7c
4
- data.tar.gz: 816b35b9b2fa41b41e4f08e851af0b125c7fc7240c0deafdd29349b68672c107
3
+ metadata.gz: 3c815c1297c45d238f61e5347b0364313ffd11756c2077ddeea3bf849a5e77aa
4
+ data.tar.gz: 203c5079d6e02159c034d70dd38dc9ea47fbd7428f02eef83f653dd6ae678d5c
5
5
  SHA512:
6
- metadata.gz: 046523126145151e5c82cfbced95b6a00edba71825c2fa87d411054e26363f4a893c3afad22a0bb013ac08779da0ebf8c25e4787adfb84cf7670dfb4c5aada50
7
- data.tar.gz: 9eb1bb09367e35cb763789857152258a4d104172fe93655f6966e8f473cc4b127df87cfd2e534cbce42415733560cffcf18009034ea77e72d43066dc3bf0d620
6
+ metadata.gz: 3dd3ae18a5b4986885a497617b4aa4a4a6d3151277231a5717115edce495c7d0b61020215ddc436f51ba66e57ae7252f623bc5279750680e3b033e444e4948d7
7
+ data.tar.gz: d86e703f660e7a0058ef76d2942a7bf933e3ef5e96141e650de12091f836ac31dd5ac81586460df5b1f98e3a5f08d35d7674cb5c2a85fa1c47b39e17b170871b
data/README.md CHANGED
@@ -106,7 +106,7 @@ mmdiscover
106
106
 
107
107
  **On the vast majority of Ruby setups (stock `arm64-darwin` or `x86_64-darwin` Ruby) this step is a no-op — nokogiri ships a precompiled binary, you can skip the rest of this section and move on.** Keep reading only if your `gem install` actually fails.
108
108
 
109
- `mmmessage --markdown` renders HTML-only message bodies as readable markdown. It needs the `reverse_markdown` gem, which has `nokogiri` as a transitive dependency:
109
+ `mmmessage --markdown` renders HTML-only message bodies as readable markdown, and (since 2.2.0) the quoted original of a reply or forward is the parent's HTML part rendered the same way, so it reads as the author laid it out. Both need the `reverse_markdown` gem, which has `nokogiri` as a transitive dependency:
110
110
 
111
111
  ```bash
112
112
  gem install reverse_markdown
@@ -114,7 +114,7 @@ gem install reverse_markdown
114
114
 
115
115
  That single command pulls `nokogiri` in automatically — no separate `gem install nokogiri` step. This is kept out of the base install because nokogiri ships a native extension. On Ruby/platform combinations without a precompiled match nokogiri falls back to compiling from source — it vendors its own libxml2/libxslt, but it does need a C compiler, which on macOS means Xcode Command Line Tools (`xcode-select --install`). If `gem install reverse_markdown` fails, that's almost certainly the cause.
116
116
 
117
- If you never use `--markdown`, you never pay any of this. If you do invoke `--markdown` without the gem installed, `mmmessage` warns with a clear install hint and falls back to the raw HTML body (it does not abort — so the in-process MCP server survives a missing optional dependency). The plugin launcher and one-line installer attempt this gem automatically and degrade the same way if it fails to build.
117
+ If you never use `--markdown` or compose from a parent, you never pay any of this. Without the gem, a reply/forward quotes the plain-text part instead (or an honest placeholder for an HTML-only parent); if you invoke `--markdown` without it, `mmmessage` warns with a clear install hint and falls back to the raw HTML body (it does not abort — so the in-process MCP server survives a missing optional dependency). The plugin launcher and one-line installer attempt this gem automatically and degrade the same way if it fails to build.
118
118
 
119
119
  ### From source (development)
120
120
 
@@ -152,6 +152,8 @@ Or add manually to `~/.claude.json` under `"mcpServers"`:
152
152
 
153
153
  For Claude Desktop, use the same command path in `claude_desktop_config.json` as shown under the one-line installer. Restart Claude Desktop after any change to server code or config.
154
154
 
155
+ Every tool answers in its text content. `search` takes a `format` argument (`csv`, the default, or `json` or `yaml`, the same as `mmsearch --format`). A JSON answer, from `search` with `format: "json"` or from `resolve_id`, is also returned as `structuredContent`, and it is the same object. Nothing else carries `structuredContent`, because clients such as Claude Code and Claude Desktop show it *instead of* the text whenever it is present. The rule and its tests are described in [docs/MCP results.md](<docs/MCP results.md>).
156
+
155
157
  ## Example usage
156
158
 
157
159
  ### `mmsearch` — find messages
@@ -195,13 +197,15 @@ mmsearch 'f acme' --limit 10 --sort from
195
197
  | `<header>:<term>` | Any indexed header contains (`delivered-to:joe`). A header this store has never seen is a usage error, not an empty result. |
196
198
  | `!<value>` | Negate, e.g. `f !smith` = From does NOT contain smith; works on dates too (`d !3d` = more than 3 days ago). |
197
199
 
198
- Dates match on the **display-zone day** — the same day the `date`/`time` output columns show. An impossible date term or combination (`d 2026-02-31`, `d >2026 d <2025`) is a usage error, not a silent empty result. Familiar foreign `key:value` tokens (`from:bob`, `date:today`, `after:2026-08-01`, `older_than:2w`) are auto-translated to quicksearch with each rewrite announced on stderr; unrecognized keys (`is:unread`) are searched as literal text, and an empty result says so.
200
+ Dates match on the **display-zone day** — the same day the `date`/`time` output columns show. An impossible date term or combination (`d 2026-02-31`, `d >2026 d <2025`) is a usage error, not a silent empty result. Familiar foreign `key:value` tokens (`from:bob`, `date:today`, `after:2026-08-01`, `older_than:2w`) are auto-translated to quicksearch with each rewrite announced on stderr; unrecognized keys (`filename:pdf`) are searched as literal text, and an empty result says so.
199
201
 
200
202
  The `--mailbox` argument accepts an account, an `account/path`, a bare mailbox name matched across accounts, or a **smart-mailbox name** (e.g. `Newsletters`, `Receipts`, `Priority`) whose filter is ANDed into the search.
201
203
 
202
204
  **Output fields.** Default columns are `flags date time direction party subject`. Prefix a field list with `+` to add to the defaults; a bare list replaces them (include `id` yourself if you want it).
203
205
 
204
- **Limiting and ordering.** `--limit N` returns the N *newest* matches, chosen after the full scan; `--limit-by KEY[:asc|desc]` changes which rows survive (`date:asc` = the N oldest). `--sort KEY[:asc|desc]` orders the emitted rows independently, so `--limit 10 --sort from` is the ten newest shown by sender. Bare `--sort asc|desc|none` still means date; a bare key reads the way the key does (date/time newest-first, text A→Z); ties break newest-first. A truncated result says so on stderr (`[limit] showing 200 of 319 matches …`) so stdout stays clean CSV. `--scan-limit N` is a different thing: it stops the *scan* after N matches in undefined order — a speed bound for slow `--all` body scans, never a way to pick rows. (Before 2.0, `--limit` had those scan-cap semantics: N arbitrary matches, however sorted.) `--offset N` skips the first N rows of that ordering before taking `--limit` — rows 1001–1200 newest-first is `--offset 1000 --limit 200`; offsets drift as mail arrives, so a date term (`d <2026-08-25`) is the stable way to page a live mailbox. `--stats` replaces the prose notices with one machine-readable line, first on stderr — `stats: {"schema":1,"matches":321,"returned":3,"scan_capped":false,…}` — whose keys are additive-only; scripts and the MCP server read that instead of parsing prose.
206
+ **Limiting and ordering.** `--limit N` returns the N *newest* matches, chosen after the full scan; `--limit-by KEY[:asc|desc]` changes which rows survive (`date:asc` = the N oldest). `--sort KEY[:asc|desc]` orders the emitted rows independently, so `--limit 10 --sort from` is the ten newest shown by sender. Bare `--sort asc|desc|none` still means date; a bare key reads the way the key does (date/time newest-first, text A→Z); ties break newest-first. A truncated result says so on stderr (`[limit] showing 200 of 319 matches …`) so stdout stays clean CSV. `--scan-limit N` is a different thing: it stops the *scan* after N matches in undefined order — a speed bound for slow `--all` body scans, never a way to pick rows. (Before 2.0, `--limit` had those scan-cap semantics: N arbitrary matches, however sorted.) `--offset N` skips the first N rows of that ordering before taking `--limit` — rows 1001–1200 newest-first is `--offset 1000 --limit 200`; offsets drift as mail arrives, so a date term (`d <2026-08-25`) is the stable way to page a live mailbox. `--stats` replaces the prose notices with one machine-readable line, first on stderr — `stats: {"schema":1,"matches":321,"returned":3,"scan_capped":false,…}` — whose keys are additive-only; scripts read that instead of parsing prose, and the MCP server's CSV search asks for it so the model sees the true match total.
207
+
208
+ **Structured output.** `--format json` or `--format yaml` writes one document on stdout in place of the CSV: `{schema, stats, fields, rows, notices}`, where `stats` is the `--stats` object, `rows` holds one object per message keyed by field name (`{"id": "183715", "subject": "…"}`), and `notices` holds every message a `--stats` CSV run would have printed on stderr after the stats line, such as query translations and zero-result hints. Truncation is reported in `stats` (`matches` against `returned`), not as a notice. On success nothing goes to stderr, so the document alone is the whole answer. JSON and YAML are the same object in two spellings. A failed run writes no document and explains on stderr, as the CSV run does. `--format csv` is the default.
205
209
 
206
210
  | Field | What it shows |
207
211
  |---|---|
@@ -237,9 +241,13 @@ mmmessage 183715 --mailmate
237
241
 
238
242
  # Render an HTML-only message as clean markdown (no-op for text/plain bodies)
239
243
  mmmessage 183715 --markdown
244
+
245
+ # Every identifier as JSON: eml_id, message_id, message_url (portable),
246
+ # mid_url (drives MailMate locally), path, mailbox
247
+ mmmessage 183715 --resolve
240
248
  ```
241
249
 
242
- `--markdown` uses `reverse_markdown` + Nokogiri preprocessing to drop `<style>`/`<script>` blocks and strip newsletter preview-text padding (zero-width chars, runs of non-breaking / figure / narrow spaces, etc.). Conversion quality is good for plain replies/threads and rough for marketing-newsletter HTML (which uses nested layout tables); the raw source is still available with `--raw`.
250
+ `--markdown` uses `reverse_markdown` + Nokogiri preprocessing (`Mailmate::HtmlMarkdown`, shared with the quoted original of a reply/forward): it drops `<head>`/`<style>`/`<script>`/comments, hidden (`display:none`) elements and tracking pixels, strips newsletter preview-text padding (zero-width chars, non-breaking spaces), and — the part that makes transactional mail readable — unwraps nested *layout* tables into flowing text while keeping real data tables (a regular grid of short cells) as markdown tables. The raw source is still available with `--raw`.
243
251
 
244
252
  ### `mmopen` — open a message in MailMate's UI
245
253
 
@@ -364,10 +372,12 @@ mm-send -t friend@example.com -c cc@example.com -s "Status update" --send-now <<
364
372
  - on to the next
365
373
  EOF
366
374
 
367
- # Attach files (positional args after options)
368
- mm-send -t friend@example.com -s "Photos" /path/to/photo1.jpg /path/to/photo2.jpg <<<"See attached."
375
+ # Attach files: list them FIRST (see below)
376
+ mm-send /path/to/photo1.jpg /path/to/photo2.jpg -t friend@example.com -s "Photos" <<<"See attached."
369
377
  ```
370
378
 
379
+ **Attachments go first.** emate's `-f`/`-t`/`-c`/`-b`/`-s`/`--header` each take any number of values, so a file path right after one of them is read as another recipient or subject. The attachment is then dropped without an error. Put attachment paths before every flag, or right after a flag that takes no value such as `--send-now`. mm-send appends its own `--markup markdown` last for the same reason (fixed in 2.2.2; earlier versions put it first, which swallowed a leading attachment and turned off markdown rendering).
380
+
371
381
  #### Replies, forwards, and threading
372
382
 
373
383
  **A `Re:` subject does not thread.** Modern clients thread on headers, so a reply without `In-Reply-To` / `References` shows up in the recipient's client as a brand-new conversation — and nothing in your own view reveals it. MailMate generates the outgoing `Message-ID` itself; that part is never your job.
@@ -385,7 +395,7 @@ mm-send -f you@x --reply-all-to 12345 --send-now <<<"body"
385
395
  mm-send -f you@x --forward 12345 -t someone@example.com <<<"FYI"
386
396
  ```
387
397
 
388
- The parent is an eml-id or an RFC Message-ID. **Fields you pass explicitly win; fields you omit follow normal reply rules**, and overriding a visible field never drops the threading headers. `--no-quote` suppresses the quoted original. `--print-prefill` prints the derived fields as JSON and sends nothing — the hook for other tools that fill their own compose form.
398
+ The parent is an eml-id or an RFC Message-ID. **Fields you pass explicitly win; fields you omit follow normal reply rules**, and overriding a visible field never drops the threading headers. `--no-quote` suppresses the quoted original (the parent's HTML part rendered to markdown when it has one, else its plain text — see `docs/Composing and threading.md`). `--print-prefill` prints the derived fields as JSON and sends nothing — the hook for other tools that fill their own compose form.
389
399
 
390
400
  Hand-assembly via `--header` still works and is the escape hatch when the parent isn't in MailMate's index. The `mailmate-mcp` `send` / `draft` tools take `in_reply_to` and `references` directly.
391
401
 
@@ -47,6 +47,8 @@ mm-send -f you@x -t them@y -s "Re: foo" \
47
47
 
48
48
  When a parent is supplied, **explicitly-passed fields always win; omitted fields follow normal reply rules** (parent's sender becomes the recipient, subject becomes `Re: <original>`, the quoted original seeds the body, reply-all additionally carries the other recipients minus your own identities).
49
49
 
50
+ **What "the quoted original" is** (2.2.0): the parent's HTML part rendered to markdown when it has one — so the quote reads as the author laid it out (headings, links, emphasis) rather than as the text/plain alternative many senders neglect — else the plain part, else an honest placeholder saying there is no readable text. Raw HTML is never quoted, and a quote is never silently empty. The rendering needs the optional `reverse_markdown` gem (the same one `mmmessage --markdown` uses); without it the plain part is used. Same in every mode; a forward wraps it in the `---------- Forwarded message ----------` header block, a reply prefixes it with `> `.
51
+
50
52
  This rule is uniform across every surface that composes from a parent — the CLI flags above and markdownr's compose popup — so a caller who learns it once can predict all of them. Overriding a visible field never drops the threading headers.
51
53
 
52
54
  ## Header safety
@@ -0,0 +1,68 @@
1
+ # MCP results
2
+
3
+ **This is the canonical description of what `mailmate-mcp` tool results look like.** The MCP code (`attach_structured_content!` in `lib/mailmate/mcp.rb`), the README, and the tool descriptions point here rather than restating it.
4
+
5
+ ## The rule
6
+
7
+ 1. **The text is always the complete answer**, in the format the caller asked for.
8
+ 2. **`structuredContent` is sent only when that answer is JSON**, and it is the same object as the text parsed as JSON. Today that is `search` with `format: "json"`, and `resolve_id`.
9
+ 3. **Errors never carry `structuredContent`.**
10
+ 4. **No tool declares an `outputSchema`.** Declaring one obliges the server to send `structuredContent` on every result of that tool, which a CSV search deliberately does not.
11
+
12
+ The caller chooses the format with an argument, such as `search`'s `format: csv | json | yaml`. That argument means the same thing as the matching CLI flag (`mmsearch --format`). The server never looks at which client is calling.
13
+
14
+ ## Why
15
+
16
+ An MCP result can carry two copies of its answer, the `content` text and `structuredContent`. **Clients pick one of the two to show, and the server cannot control which.** Measured on 2026-11-28 against Claude Code 2.1.330, using a test server that put different markers in each:
17
+
18
+ | The tool returned | The model received |
19
+ |---|---|
20
+ | Text only | The text |
21
+ | Text and `structuredContent` | Only `structuredContent`, serialized to JSON |
22
+ | `structuredContent` only | `structuredContent`, serialized to JSON |
23
+ | Both, with an `outputSchema` declared | Only `structuredContent` |
24
+ | Both, with `isError: true` | Only the text |
25
+
26
+ Claude Desktop behaves the same way according to the report in brianmd/mailmate#2. Other clients may show only the text. A server that puts different information in the two copies is therefore wrong for some client, whichever way it splits them.
27
+
28
+ That is what happened from 2.1.0 to 2.2.2. A CSV `search` also sent `structuredContent: {stats: …}`, so Claude Code and Claude Desktop showed the match count and none of the rows, and lost the query-translation notice too.
29
+
30
+ **Why not choose by client?** Each client names itself in `initialize` (`clientInfo`), but its behavior changes between versions without notice, and the protocol leaves the choice to the client. A table of client quirks would quietly go stale. Making both copies complete works for every client.
31
+
32
+ **Why not a flag for "structured or text"?** The model making the call cannot choose which copy its client shows, so such a flag would really select an envelope the client may ignore. The thing the caller does choose is the format of the data, and the rule above derives the envelope from it.
33
+
34
+ ## How it is tested
35
+
36
+ - `test/test_mcp_protocol.rb` starts the real `exe/mailmate-mcp` against a throwaway mail store, speaks JSON-RPC to it, and checks the result of every read-side tool except `verify` against the rule. Run against 2.2.2 it fails on the CSV search.
37
+ - `test/test_mcp_contract.rb` checks, for every tool and every input property, that the property changes what reaches the CLI, that the CLI's own parser accepts the arguments built (including a value that starts with a dash), and that arguments the schema does not allow are rejected. `send` and `draft` pass most flags through to MailMate's `emate`, so for those two the check is our own flag parsing plus a list of the `emate` flags the tools may use. Because every tool runs its CLI in-process, the CLI tests then cover the behavior behind each tool.
38
+ - `test/test_mcp.rb` holds the specific mappings, such as which `search` format sends `structuredContent`.
39
+
40
+ ## Arguments are checked against the schema
41
+
42
+ Every call is checked against the tool's own `inputSchema` before anything runs (`argument_problems` in `lib/mailmate/mcp.rb`). An unknown argument, a missing required one, a value of the wrong type, or a value outside an `enum` is rejected with a result marked `isError` that lists every problem, suggests the nearest valid name for a misspelling, and lists the valid arguments. It is a tool error and not a protocol error, so the model sees the message and can correct the call, as 2025-11-25 asks.
43
+
44
+ Before 2.3.0 the handlers read the keys they knew and ignored the rest. A misspelled `limt: 5` ran an unlimited search, `headers_only: "false"` turned the flag on because a non-empty string is truthy, and `limit: "ten"` became `--limit 0`, each without a word.
45
+
46
+ Two leniencies are deliberate, and both are lossless. `null` means "not given", for every argument. An integer is accepted where a string is expected, because ids are typed as strings and often arrive as integers.
47
+
48
+ ## Values are never read as options
49
+
50
+ Each tool turns its arguments into a command line for the matching CLI, and two rules keep a value from being mistaken for an option.
51
+
52
+ **Queries, ids and action words follow a `--`.** That marker ends option parsing, so a value that starts with a dash stays a value. Before 2.3.0 the documented negation `-is:unread` failed as an invalid option, a query of `-a` silently became `--all`, and a Message-ID that starts with a dash could not be read. A search given `fields` but no `query` also sent an empty query, which searched all mail, where the default is today's.
53
+
54
+ **`send` and `draft` refuse option-shaped values.** Their arguments end up on the command line of MailMate's `emate`, which reads any option-shaped token as an option wherever it sits. A `from`, `to`, `cc`, `bcc` or `subject` that starts with a dash followed by a letter is refused, an attachment must be an absolute path, and only one of `reply_to`, `reply_all_to` and `forward` may be given. Before 2.3.0 an attachment of `--send-now=true` passed straight through, and `mm-draft` refused only the exact token `--send-now`. `mm-draft` now refuses both spellings, on every token. Whether `emate` honors the `=true` spelling was not tested, since the test would send mail.
55
+
56
+ ## Results are always valid UTF-8
57
+
58
+ A JSON string must be valid UTF-8, and mail is not always. `message` with `raw: true` returns the file's bytes, and some messages carry stray Latin-1 bytes. Tool output is converted before it is sent: valid UTF-8 passes through unchanged and any other byte becomes U+FFFD, the replacement character. Before 2.3.0 such a result could not be serialized. For exact bytes, read the file at the `path` that `resolve_id` returns.
59
+
60
+ ## Protocol versions
61
+
62
+ `initialize` echoes the client's requested version when the server supports it. That is the 2025-11-25 lifecycle rule. The supported list is `SUPPORTED_PROTOCOL_VERSIONS` in `lib/mailmate/mcp.rb`: 2025-11-25, 2025-06-18 and 2024-11-05. The server behaves the same under all three. The newer fields it sends, `structuredContent` and tool `title` from 2025-06-18 and tool annotations from 2025-03-26, are extra fields that an older client ignores. Before 2.3.0 the server answered 2024-11-05 to every client while already sending those fields.
63
+
64
+ For any other request the server offers the newest version it supports that is not newer than the request, and its newest of all when there is none. 2025-03-26 is left off the list on purpose: it is the one revision that obliges a server to accept JSON-RPC batches, which this server rejects. A client asking for it is offered 2024-11-05, which a client of that age also speaks.
65
+
66
+ Two 2025-11-25 rules apply directly. An unknown tool is a JSON-RPC error (`-32602`), while a tool that ran and failed is a result with `isError`. And JSON-RPC batches, which exist only in 2025-03-26, get an `Invalid Request` error (`-32600`). Before 2.3.0 a batch, or any line that was not a JSON object, crashed the server. A message without an `id` is a notification, so it is never answered and never runs a tool.
67
+
68
+ The 2026-07-28 revision is not supported. It drops the `initialize` handshake: each request carries its own version, servers must implement `server/discover`, and every result carries `resultType`. Clients still open with `initialize` (Claude Code 2.1.330 requests 2025-11-25), and that revision allows a server to support both styles, so adding it can wait until clients start using it.
@@ -25,7 +25,11 @@ module Mailmate
25
25
  # Returns the exit status. Refuses `--send-now` (exit 2); otherwise
26
26
  # delegates verbatim to `Mailmate::CLI::Send`.
27
27
  def run(argv)
28
- if argv.include?("--send-now")
28
+ # emate (CLI11) also takes the `--send-now=VALUE` spelling, and reads
29
+ # an option-shaped token as an option wherever it sits, so the check
30
+ # is on every token and on both spellings. An exact-string match
31
+ # here let `--send-now=true` through.
32
+ if argv.any? { |arg| arg.to_s.match?(/\A--send-now(\z|=)/) }
29
33
  warn "mm-draft: refusing --send-now — mm-draft only ever creates drafts. Use mm-send to send."
30
34
  return 2
31
35
  end
@@ -1,6 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "optparse"
4
+ require "json"
5
+ require "mailmate/eml_lookup"
6
+ require "mailmate/header_reader"
7
+ require "mailmate/mid_url"
4
8
  # `mail` is required lazily inside run() — the --raw and --mailmate paths
5
9
  # never parse the message, so they shouldn't pay ~50 ms loading the gem.
6
10
 
@@ -35,6 +39,8 @@ module Mailmate
35
39
  return 1
36
40
  end
37
41
 
42
+ return print_identifiers(eml_id, path) if opts[:resolve]
43
+
38
44
  if opts[:mailmate]
39
45
  require_relative "open"
40
46
  # Hand off to mmopen — same id resolution already done, but Open re-resolves
@@ -56,9 +62,9 @@ module Mailmate
56
62
  end
57
63
 
58
64
  def parse_options(argv)
59
- opts = { raw: false, text_only: false, mailmate: false, markdown: false }
65
+ opts = { raw: false, text_only: false, mailmate: false, markdown: false, resolve: false }
60
66
  OptionParser.new do |o|
61
- o.banner = "Usage: mmmessage <id> [--raw|--text-only|--mailmate|--markdown]"
67
+ o.banner = "Usage: mmmessage <id> [--raw|--text-only|--mailmate|--markdown|--resolve]"
62
68
  o.separator ""
63
69
  o.separator "<id> can be a local eml-id (e.g. 183715), an RFC Message-ID"
64
70
  o.separator "(with or without angle brackets, e.g. <abc@example.com>), or"
@@ -68,23 +74,37 @@ module Mailmate
68
74
  o.on("--text-only", "Output decoded body only (no headers block)") { opts[:text_only] = true }
69
75
  o.on("--mailmate", "Open in MailMate's UI instead of printing (alias for `mmopen <id>`)") { opts[:mailmate] = true }
70
76
  o.on("--markdown", "Render HTML body as clean markdown (no-op for plain-text messages)") { opts[:markdown] = true }
77
+ o.on("--resolve", "Print the message's identifiers as JSON instead: eml_id, message_id, message_url (portable), mid_url (drives MailMate locally), path, mailbox") { opts[:resolve] = true }
71
78
  end.parse!(argv)
72
79
  opts
73
80
  end
74
81
 
82
+ # `--resolve`: every identifier for one message, as one JSON object.
83
+ # The MCP `resolve_id` tool is this, verbatim.
84
+ def print_identifiers(eml_id, path)
85
+ message_id = Mailmate::HeaderReader.message_id(path)
86
+ $stdout.puts JSON.pretty_generate(
87
+ eml_id: eml_id,
88
+ message_id: message_id,
89
+ message_url: message_id ? Mailmate::MidUrl.message_url_for(message_id) : nil,
90
+ mid_url: message_id ? Mailmate::MidUrl.for(message_id) : nil,
91
+ path: path,
92
+ mailbox: Mailmate::EmlLookup.mailbox_for(path),
93
+ )
94
+ 0
95
+ end
96
+
75
97
  def usage_error(msg)
76
98
  warn "mmmessage: #{msg}"
77
- warn "Usage: mmmessage <id> [--raw|--text-only|--mailmate|--markdown]"
99
+ warn "Usage: mmmessage <id> [--raw|--text-only|--mailmate|--markdown|--resolve]"
78
100
  warn " <id> is either an eml-id (digits) or an RFC Message-ID."
79
101
  2
80
102
  end
81
103
 
82
104
  def print_headers(mail, eml_id, path)
83
- imap_root = Mailmate.config.imap_root
84
- mailbox = path.sub("#{imap_root}/", "").sub(%r{/Messages/[^/]+\.eml\z}, "")
85
105
  $stdout.puts "eml-id: #{eml_id}"
86
106
  $stdout.puts "path: #{path}"
87
- $stdout.puts "mailbox: #{mailbox}"
107
+ $stdout.puts "mailbox: #{Mailmate::EmlLookup.mailbox_for(path)}"
88
108
  $stdout.puts "from: #{Array(mail.from).join(", ")}" if mail.from
89
109
  $stdout.puts "to: #{Array(mail.to).join(", ")}" if mail.to
90
110
  $stdout.puts "cc: #{Array(mail.cc).join(", ")}" if mail.cc
@@ -146,42 +166,21 @@ module Mailmate
146
166
  ct.include?("text/html") || body =~ /\A\s*<(?:!doctype html|html|body|head)\b/i
147
167
  end
148
168
 
149
- # HTML → clean markdown for terminal reading. Three preprocessing /
150
- # postprocessing passes beyond plain reverse_markdown:
151
- # 1. Drop <style> and <script> blocks before conversion — pure clutter
152
- # that reverse_markdown otherwise dumps as inline text.
153
- # 2. Strip zero-width spacers that newsletters use to control inbox
154
- # preview text (U+034F, U+200B/C/D, U+FEFF). Without this, you get
155
- # long runs of `͏ ` in the output.
156
- # 3. Collapse 3+ consecutive blank lines into a single blank line.
169
+ # HTML → clean markdown for terminal reading, via the shared converter
170
+ # (Mailmate::HtmlMarkdown — ReplyPrefill quotes HTML-only parents with
171
+ # the same passes). Degrades to the raw HTML with a hint rather than
172
+ # `exit`: a library method must not kill its host, and the in-process
173
+ # MCP server would otherwise die on the SystemExit (its dispatch rescues
174
+ # StandardError only).
157
175
  def html_to_markdown(html)
158
- begin
159
- require "nokogiri"
160
- require "reverse_markdown"
161
- rescue LoadError => e
162
- warn "mmmessage --markdown needs the reverse_markdown gem (which pulls nokogiri)."
163
- warn "Install it with: gem install reverse_markdown"
164
- warn "(underlying: #{e.message}) — falling back to raw HTML."
165
- # Degrade to the raw HTML rather than `exit`: a library method must
166
- # not kill its host, and the in-process MCP server would otherwise
167
- # die on the SystemExit (its dispatch rescues StandardError only).
168
- return html
169
- end
170
- doc = Nokogiri::HTML(html)
171
- doc.css("style, script").remove
172
- md = ReverseMarkdown.convert(doc.to_html)
173
- # U+034F combining grapheme joiner, U+200B ZWSP, U+200C ZWNJ,
174
- # U+200D ZWJ, U+FEFF BOM/ZWNBSP — newsletter preview-text padding.
175
- md.gsub!(/[\u034F\u200B\u200C\u200D\uFEFF]/, "")
176
- # Convert non-breaking spaces to regular spaces so rstrip can collapse
177
- # them. Newsletter preview-text padding often uses runs of &nbsp; which
178
- # Ruby's .rstrip leaves alone otherwise.
179
- md.gsub!(/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/, " ")
180
- # Strip trailing whitespace per line - the spaces between the
181
- # now-removed zero-width chars otherwise leave long whitespace runs.
182
- md = md.lines.map(&:rstrip).join("\n")
183
- md.gsub!(/\n{3,}/, "\n\n")
184
- md.strip
176
+ require_relative "../html_markdown"
177
+ md = Mailmate::HtmlMarkdown.convert(html)
178
+ return md if md
179
+
180
+ warn "mmmessage --markdown needs the reverse_markdown gem (which pulls nokogiri)."
181
+ warn "Install it with: gem install reverse_markdown"
182
+ warn "Falling back to raw HTML."
183
+ html
185
184
  end
186
185
  end
187
186
  end
@@ -5,6 +5,7 @@ require "optparse"
5
5
  require "date"
6
6
  require "csv"
7
7
  require "json"
8
+ require "yaml"
8
9
  require "stringio"
9
10
 
10
11
  module Mailmate
@@ -89,7 +90,7 @@ module Mailmate
89
90
  mailbox: "all", limit: nil, offset: 0, scan_limit: nil, limit_by: DEFAULT_LIMIT_BY,
90
91
  headers_only: false, all: false,
91
92
  exclude_quoted: false,
92
- header: true, align: true, sort: DEFAULT_SORT, stats: false,
93
+ header: true, align: true, sort: DEFAULT_SORT, stats: false, format: "csv",
93
94
  }
94
95
 
95
96
  parser = build_parser(opts)
@@ -100,6 +101,7 @@ module Mailmate
100
101
  return 2
101
102
  end
102
103
 
104
+ return run_document(argv, opts) unless opts[:format] == "csv"
103
105
  return search(argv, opts) unless opts[:stats]
104
106
 
105
107
  # --stats promises one machine-readable line FIRST on stderr, but
@@ -120,6 +122,81 @@ module Mailmate
120
122
  end
121
123
  end
122
124
 
125
+ # `--format json|yaml`: ONE document on stdout carrying everything the
126
+ # CSV run says across both streams: the stats object, the field list,
127
+ # the rows (one object per row, keyed by field name), and every notice
128
+ # the run would have written to stderr (translation, dead-branch and
129
+ # zero-result hints), one string per notice. Nothing is left on stderr
130
+ # on success, because a consumer reading only the document (an MCP
131
+ # client that shows only structuredContent, say) must not lose a
132
+ # notice. JSON and YAML are two spellings of the same object; the
133
+ # stats are the `--stats` object, so `--stats` adds nothing here. A
134
+ # failed run (usage error, unknown field, no mailbox) writes no
135
+ # document and says why on stderr, exactly as the CSV run does.
136
+ FORMATS = %w[csv json yaml].freeze
137
+ DOCUMENT_SCHEMA = 1
138
+
139
+ # Records each write separately, so one `warn` stays one notice even
140
+ # when it spans lines.
141
+ class NoticeCollector < StringIO
142
+ attr_reader :notices
143
+
144
+ def initialize
145
+ super
146
+ @notices = []
147
+ end
148
+
149
+ def write(*parts)
150
+ @notices << parts.join.chomp
151
+ super
152
+ end
153
+ end
154
+
155
+ def run_document(argv, opts)
156
+ opts[:stats] = true # fills stats_result; suppresses the [limit] prose it replaces
157
+ opts[:document] = {} # emit_output stores fields + rows here instead of printing
158
+ collector = NoticeCollector.new
159
+ real_err = $stderr
160
+ $stderr = collector
161
+ code =
162
+ begin
163
+ search(argv, opts)
164
+ ensure
165
+ $stderr = real_err
166
+ end
167
+ unless code.zero? && opts[:stats_result]
168
+ $stderr.print collector.string
169
+ return code
170
+ end
171
+
172
+ fields = opts[:document][:fields]
173
+ doc = {
174
+ schema: DOCUMENT_SCHEMA,
175
+ stats: opts[:stats_result],
176
+ fields: fields,
177
+ rows: opts[:document][:rows].map { |cells| fields.zip(cells.map { document_text(_1) }).to_h },
178
+ notices: collector.notices,
179
+ }
180
+ # One object, two spellings: round-trip through JSON so YAML sees
181
+ # plain string keys and the two can never disagree on content.
182
+ plain = JSON.parse(JSON.generate(doc))
183
+ $stdout.puts(opts[:format] == "yaml" ? YAML.dump(plain) : JSON.generate(plain))
184
+ 0
185
+ end
186
+
187
+ # A cell as it goes into the document. JSON strings must be valid
188
+ # UTF-8, and a cell can arrive tagged binary or carrying a stray
189
+ # Latin-1 byte from a header or an IMAP keyword. Valid UTF-8 passes
190
+ # through untouched; any other byte becomes U+FFFD, so one odd
191
+ # message cannot cost the caller the whole document.
192
+ def document_text(cell)
193
+ return cell unless cell.is_a?(String)
194
+ return cell if cell.encoding == Encoding::UTF_8 && cell.valid_encoding?
195
+
196
+ text = cell.dup.force_encoding(Encoding::UTF_8)
197
+ text.valid_encoding? ? text : text.scrub("�")
198
+ end
199
+
123
200
  # The `--stats` contract: this prefix, then one JSON object, on the
124
201
  # first stderr line. `matches`, `returned` and `scan_capped` are always
125
202
  # present; keys are additive-only, and `schema` increments only on a
@@ -140,7 +217,9 @@ module Mailmate
140
217
  if (notice = Mailmate::SearchSyntax.translation_notice(translations))
141
218
  warn notice
142
219
  end
143
- fields_arg = (opts[:fields] || argv[1] || DEFAULT_FIELDS).to_s.strip
220
+ # A blank fields list means "not given": zero columns is never what
221
+ # anyone asked for, and it printed one empty line per message.
222
+ fields_arg = [opts[:fields], argv[1]].map { _1.to_s.strip }.find { !_1.empty? } || DEFAULT_FIELDS
144
223
  # `+...` means "defaults plus these"; bare list = exactly those columns.
145
224
  # Defaults already include `id` as the first column, so `+x` keeps id
146
225
  # automatic while a bare list lets callers omit it (useful for
@@ -277,6 +356,7 @@ module Mailmate
277
356
  # for existing invocations), `none` (sort only), `KEY`, or `KEY:DIR`.
278
357
  def parse_order(value, allow_none: false)
279
358
  v = value.to_s.strip
359
+ raise OptionParser::InvalidArgument, "an empty value (give a field, asc or desc)" if v.empty?
280
360
  return :none if v == "none" && allow_none
281
361
  return { key: "date", dir: v.to_sym } if %w[asc desc].include?(v)
282
362
  key, dir = v.split(":", 2)
@@ -358,7 +438,8 @@ module Mailmate
358
438
  OptionParser.new do |o|
359
439
  o.banner = "Usage: mmsearch [search-string] [fields] [options]"
360
440
  o.separator ""
361
- o.separator "Search MailMate's `.eml` files. Output is CSV with column-aligned padding."
441
+ o.separator "Search MailMate's `.eml` files. Output is CSV with column-aligned padding,"
442
+ o.separator "or one JSON/YAML document with --format."
362
443
  o.separator ""
363
444
  o.separator "POSITIONAL ARGS"
364
445
  o.separator " search-string Quicksearch expression. Default: 'd 1d'. Pass '' to disable."
@@ -371,7 +452,10 @@ module Mailmate
371
452
  o.on("--mailbox X", "Mailbox to search (default: all)") { |v| opts[:mailbox] = v }
372
453
  o.on("--fields F", "Fields list (alt to 2nd positional)") { |v| opts[:fields] = v }
373
454
  o.on("--limit N", Integer,
374
- "Return at most N rows: the top N by --limit-by (default: the N newest), taken after the full scan. Announces truncation on stderr.") { |n| opts[:limit] = n }
455
+ "Return at most N rows: the top N by --limit-by (default: the N newest), taken after the full scan. Announces truncation on stderr.") { |n|
456
+ raise OptionParser::InvalidArgument, "#{n}: limit cannot be negative" if n.negative?
457
+ opts[:limit] = n
458
+ }
375
459
  o.on("--limit-by KEY[:DIR]",
376
460
  "Which rows --limit keeps. KEY is any output field; DIR is asc|desc (bare date/time = desc, text keys = asc). Default: date:desc") { |v| opts[:limit_by] = parse_order(v) }
377
461
  o.on("--offset N", Integer,
@@ -380,7 +464,10 @@ module Mailmate
380
464
  opts[:offset] = n
381
465
  }
382
466
  o.on("--scan-limit N", Integer,
383
- "Stop SCANNING after N matches, in undefined order — a speed bound for slow --all body scans, never a way to pick rows. Announces on stderr.") { |n| opts[:scan_limit] = n }
467
+ "Stop SCANNING after N matches, in undefined order — a speed bound for slow --all body scans, never a way to pick rows. Announces on stderr.") { |n|
468
+ raise OptionParser::InvalidArgument, "#{n}: scan-limit must be at least 1" if n < 1
469
+ opts[:scan_limit] = n
470
+ }
384
471
  o.on("--headers-only", "Skip body matching entirely") { opts[:headers_only] = true }
385
472
  o.on("--all", "Include un-indexed messages in body matching by lazily reading and parsing each .eml. Slow (tens of seconds to minutes on large archives). Default behavior matches MailMate's UI: only check messages MailMate has body-indexed — fast, but bounded.") { opts[:all] = true }
386
473
  o.on("--exclude-quoted", "Match body only against #unquoted text — skip MailMate's #quoted index (forwarded/replied-to text). Tightens search to fresh content; gets you closer to MailMate UI's body-search result set, at the cost of missing hits in quoted sections.") { opts[:exclude_quoted] = true }
@@ -390,6 +477,8 @@ module Mailmate
390
477
  "Order of the emitted rows. asc|desc|none alone mean date; or any output field, e.g. from, subject:desc (bare date/time = desc, text keys = asc). Ties break newest-first. Default: date:asc") { |v| opts[:sort] = parse_order(v, allow_none: true) }
391
478
  o.on("--stats",
392
479
  "Write one machine-readable line FIRST on stderr — stats: {\"schema\":1,\"matches\":M,\"returned\":N,\"scan_capped\":false,...} — in place of the [limit]/[scan-limit] prose. Keys are additive-only; other stderr follows it.") { opts[:stats] = true }
480
+ o.on("--format FMT", FORMATS,
481
+ "csv (default) | json | yaml. json/yaml write ONE document on stdout: {schema, stats, fields, rows: [{field: value}], notices: [...]}, i.e. the --stats object, one object per row, and every stderr notice. --no-header, --no-align and --stats don't apply.") { |v| opts[:format] = v }
393
482
  o.on("--european",
394
483
  "Slash dates are day-first: d 9/8/2026 = Aug 9 (default: month-first American)") { opts[:european] = true }
395
484
  o.separator ""
@@ -1415,7 +1504,7 @@ module Mailmate
1415
1504
  case field
1416
1505
  when "id" then eml_id
1417
1506
  when "path" then path
1418
- when "mailbox" then path.sub("#{Mailmate.config.imap_root}/", "").sub(%r{/Messages/[^/]+\.eml\z}, "")
1507
+ when "mailbox" then Mailmate::EmlLookup.mailbox_for(path)
1419
1508
  when "date"
1420
1509
  t = message_time(eml_id, mail)
1421
1510
  Mailmate.localize(t)&.strftime("%Y-%m-%d")
@@ -1550,6 +1639,12 @@ module Mailmate
1550
1639
  end
1551
1640
 
1552
1641
  def emit_output(rows, fields, opts)
1642
+ if opts[:document]
1643
+ opts[:document][:fields] = fields
1644
+ opts[:document][:rows] = rows
1645
+ return
1646
+ end
1647
+
1553
1648
  header_row = fields.map { |f| HEADER_LABELS[f] || f }
1554
1649
 
1555
1650
  if opts[:align]
@@ -30,6 +30,14 @@ module Mailmate
30
30
  explicitly win; fields you omit follow normal reply rules. --header
31
31
  stays available as the escape hatch when the parent isn't indexed.
32
32
 
33
+ Attachments
34
+ Attachments are bare file paths. emate's address, subject and header
35
+ flags take any number of values, so a path right after one of them
36
+ is read as another recipient or subject, silently. List attachments
37
+ FIRST, or after a flag that takes no value such as --send-now.
38
+
39
+ mm-send /path/a.pdf -t friend@x -s "Docs" --send-now <<<"Attached."
40
+
33
41
  Identity selection
34
42
  `-f <address>` picks which of MailMate's configured identities sends.
35
43
  Without `-f`, MailMate uses its default identity. See `mmdiscover` to
@@ -81,7 +89,7 @@ module Mailmate
81
89
  # interactive `mm-send --help` waiting for Ctrl-D.
82
90
  body = help ? "" : $stdin.read.to_s
83
91
  body = append_quote(body, derived) if derived
84
- out, err, status = Open3.capture3(EMATE_PATH, "mailto", "--markup", "markdown", *argv, stdin_data: body)
92
+ out, err, status = Open3.capture3(EMATE_PATH, "mailto", *emate_args(argv), stdin_data: body)
85
93
  $stdout.write(out)
86
94
  $stderr.write(err)
87
95
  # exitstatus is nil for a signal-killed child; the exe shims do
@@ -89,6 +97,20 @@ module Mailmate
89
97
  status.exitstatus || 1
90
98
  end
91
99
 
100
+ # The enforced `--markup markdown` goes LAST. emate parses with CLI11,
101
+ # where -f/-t/-c/-b/-r/-s/-m/--header each take any number of values:
102
+ # every bare word after one of them is read as another value until the
103
+ # next flag. Prepended, `--markup markdown photo.jpg -t …` read the
104
+ # photo as a second markup value, which dropped the attachment AND the
105
+ # markdown rendering while emate still exited 0 (2026-10-13: tenant
106
+ # mail from markdownr's compose popup, which lists attachments first).
107
+ # Last, nothing follows it to swallow. A caller's `--` ends option
108
+ # parsing, so the flag goes in front of that instead.
109
+ def emate_args(argv)
110
+ at = argv.index("--") || argv.length
111
+ argv.dup.insert(at, "--markup", "markdown")
112
+ end
113
+
92
114
  # Flags this wrapper consumes itself. Everything else in argv is emate's
93
115
  # and passes through untouched — that pass-through is the design, so the
94
116
  # scan below is deliberately literal rather than an OptionParser (which
@@ -47,8 +47,15 @@ module Mailmate
47
47
 
48
48
  # Derived paths. Each follows from app_support_dir; if a user has a
49
49
  # non-default MailMate install, overriding app_support_dir flows through.
50
+ # MailMate stores mail under `Messages.noindex/` on most installs, but some
51
+ # long-lived installs still use the older `Messages/` folder name. Prefer
52
+ # `Messages.noindex` (also the answer when neither exists yet), and fall
53
+ # back to `Messages` only when that is the one actually on disk.
50
54
  def imap_root
51
- File.join(app_support_dir, "Messages.noindex", "IMAP")
55
+ noindex = File.join(app_support_dir, "Messages.noindex", "IMAP")
56
+ legacy = File.join(app_support_dir, "Messages", "IMAP")
57
+ return legacy if !File.directory?(noindex) && File.directory?(legacy)
58
+ noindex
52
59
  end
53
60
 
54
61
  def db_headers
@@ -24,6 +24,14 @@ module Mailmate
24
24
  via_index(eml_id) || via_glob(eml_id)
25
25
  end
26
26
 
27
+ # The account/mailbox path a message lives in, e.g.
28
+ # "acct/INBOX.mailbox": the path below the IMAP root, minus the
29
+ # trailing "/Messages/<id>.eml". The one derivation behind mmsearch's
30
+ # `mailbox` column, mmmessage's header block and `mmmessage --resolve`.
31
+ def self.mailbox_for(path)
32
+ path.sub("#{Mailmate.config.imap_root}/", "").sub(%r{/Messages/[^/]+\.eml\z}, "")
33
+ end
34
+
27
35
  # Reverse-lookup: given an RFC Message-ID (with or without angle brackets),
28
36
  # return the local eml-id (integer) or nil. Backed by a value→id map built
29
37
  # once per index snapshot (one O(n) pass, then O(1) lookups) — the map is