nextcloud-client 0.211.0__py3-none-any.whl

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.
@@ -0,0 +1,825 @@
1
+ """Client for the Nextcloud Mail app API.
2
+
3
+ Uses two endpoint types:
4
+
5
+ 1. **OCS routes** — ``/ocs/v2.php/apps/mail/message/...`` — for reading full messages
6
+ (body + metadata) and the raw RFC 2822 source. Works with Basic Auth (App
7
+ Password) via the OCS-APIRequest header. These routes are registered in the
8
+ ``'ocs'`` section of the Mail app's ``routes.php``.
9
+
10
+ 2. **Direct app routes** — ``/index.php/apps/mail/api/...`` — for listing accounts,
11
+ mailboxes, and messages, downloading attachments, the two-step outbox send, the
12
+ two-step draft save, and every write operation (flags, tags, move, delete),
13
+ none of which has an OCS equivalent. These REST resource routes (from
14
+ ``'resources'`` in ``routes.php``) are CSRF-gated for browser sessions, but
15
+ Nextcloud exempts any request carrying the ``OCS-APIRequest: true`` header from
16
+ the CSRF check — so Basic Auth (App Password) + that header is sufficient. No
17
+ ``requesttoken`` round-trip is needed (verified end-to-end against a live Mail
18
+ 5.x backend; see the GreenMail integration tests).
19
+
20
+ Attachment downloads use the direct route ``/api/messages/{id}/attachment/{id}``,
21
+ which returns the raw file bytes (via core's ``DownloadResponse``). The OCS
22
+ ``/message/{id}/attachment/{id}`` route is unreliable across Mail versions — on
23
+ some setups it returns HTTP 200 with an empty, non-JSON body (see GH #989).
24
+ """
25
+
26
+ import base64
27
+ import logging
28
+ from email.message import Message
29
+ from typing import Any
30
+ from urllib.parse import quote
31
+
32
+ from httpx2 import HTTPStatusError, RequestError, Response
33
+
34
+ from .base import BaseNextcloudClient
35
+ from .ocs import (
36
+ OCS_REQUEST_HEADERS,
37
+ describe_ocs_failure,
38
+ parse_ocs_envelope,
39
+ )
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ # Nextcloud's primary blue. Shared with the nc_mail_create_tag tool so the two
44
+ # defaults cannot drift into creating differently-coloured tags for the same
45
+ # nominal "default".
46
+ DEFAULT_TAG_COLOR = "#0082c9"
47
+
48
+
49
+ def _ocs_response(response: Response) -> Any:
50
+ """Unwrap the OCS envelope from a response and validate the meta status.
51
+
52
+ Args:
53
+ response: The httpx2 response object from an OCS endpoint.
54
+
55
+ Returns:
56
+ The ``ocs.data`` payload.
57
+
58
+ Raises:
59
+ HTTPStatusError: If the OCS meta indicates failure.
60
+ RequestError: If the response is not valid JSON.
61
+ """
62
+ try:
63
+ body = response.json()
64
+ except Exception:
65
+ raise RequestError(
66
+ f"Response is not valid JSON: {response.text[:200]}"
67
+ ) from None
68
+
69
+ if not isinstance(body, dict):
70
+ raise RequestError(
71
+ f"Unexpected response format: expected dict, got {type(body).__name__}"
72
+ )
73
+
74
+ # These shape checks are not redundant with parse_ocs_envelope: it reports
75
+ # a malformed body as a 500 envelope, whereas this client's contract is to
76
+ # raise RequestError for a body that is not an OCS response at all. Callers
77
+ # distinguish "the server said no" from "that was not OCS", so the checks
78
+ # stay ahead of the shared parser.
79
+ ocs = body.get("ocs")
80
+ if not isinstance(ocs, dict):
81
+ raise RequestError(
82
+ f"Unexpected OCS format: expected dict, got {type(ocs).__name__}"
83
+ )
84
+
85
+ # Parsing and failure wording are shared with the other OCS clients; the
86
+ # >= 400 rule and the HTTPStatusError contract stay local, since callers
87
+ # here branch on status_code and a stricter rule would be a behaviour
88
+ # change rather than a refactor.
89
+ envelope = parse_ocs_envelope(body)
90
+
91
+ if envelope.status_code >= 400:
92
+ message = describe_ocs_failure(envelope.status_code, envelope.message)
93
+ # Synthesise a Response-like object so callers can check status_code
94
+ synthetic = Response(status_code=envelope.status_code, text=message)
95
+ raise HTTPStatusError(message, request=response.request, response=synthetic)
96
+
97
+ return envelope.data
98
+
99
+
100
+ class MailClient(BaseNextcloudClient):
101
+ """Client for the Nextcloud Mail app API.
102
+
103
+ Uses a combination of OCS and direct routes to cover the full mail workflow
104
+ (list accounts → browse mailboxes → list messages → read message → send
105
+ reply) with the correct authentication for each endpoint.
106
+
107
+ Requests go through :meth:`BaseNextcloudClient._make_request`, which routes
108
+ bare ``/apps/...`` paths through ``_resolve_url`` (prepending ``/index.php``,
109
+ the universal entry point that works without pretty-URL rewriting — issue
110
+ #732), applies 429 retry, tracing, and ``raise_for_status``. ``/ocs/...``
111
+ paths pass through ``_resolve_url`` unchanged.
112
+ """
113
+
114
+ # OCS endpoints — work with Basic Auth + OCS‑APIRequest header alone.
115
+ OCS_BASE = "/ocs/v2.php/apps/mail"
116
+
117
+ # Direct API endpoints — CSRF-exempt via the OCS-APIRequest header. Written
118
+ # as bare ``/apps/...`` paths (``_resolve_url`` prepends ``/index.php``).
119
+ API_BASE = "/apps/mail/api"
120
+
121
+ # Both route families want JSON, so they share this ``Accept``-only set. The
122
+ # OCS-APIRequest header that authenticates the OCS routes and CSRF-exempts
123
+ # the direct ones is not in it: the httpx2 client sends that on every request
124
+ # (``nextcloud_client.http.NEXTCLOUD_DEFAULT_HEADERS``).
125
+ _API_JSON_HEADERS = dict(OCS_REQUEST_HEADERS)
126
+
127
+ app_name = "mail"
128
+
129
+ # ------------------------------------------------------------------
130
+ # Low‑level request helpers
131
+ # ------------------------------------------------------------------
132
+
133
+ async def _ocs_get(self, path: str, params: dict[str, Any] | None = None) -> Any:
134
+ """GET an OCS endpoint and unwrap its envelope.
135
+
136
+ Args:
137
+ path: Path relative to :attr:`OCS_BASE` (e.g. ``/message/1``).
138
+ params: Optional query-string parameters.
139
+
140
+ Returns:
141
+ The ``ocs.data`` payload (list or dict).
142
+ """
143
+ query: dict[str, Any] = {"format": "json"}
144
+ if params:
145
+ query.update(params)
146
+
147
+ response = await self._make_request(
148
+ "GET",
149
+ f"{self.OCS_BASE}{path}",
150
+ params=query,
151
+ headers=self._API_JSON_HEADERS,
152
+ )
153
+ # ``_make_request`` (base) already raised on any non-2xx status; an OCS
154
+ # meta failure arrives as HTTP 200 and is handled by ``_ocs_response``.
155
+ return _ocs_response(response)
156
+
157
+ async def _api_get(self, path: str, params: dict[str, Any] | None = None) -> Any:
158
+ """GET a direct API endpoint (CSRF-exempt via the OCS-APIRequest header).
159
+
160
+ Args:
161
+ path: Path relative to :attr:`API_BASE` (e.g. ``/accounts``).
162
+ params: Optional query-string parameters.
163
+
164
+ Returns:
165
+ The parsed JSON response body.
166
+ """
167
+ response = await self._make_request(
168
+ "GET",
169
+ f"{self.API_BASE}{path}",
170
+ params=params,
171
+ headers=self._API_JSON_HEADERS,
172
+ )
173
+ # ``_make_request`` (base) already raised on any non-2xx status.
174
+ return response.json()
175
+
176
+ async def _api_write(
177
+ self, method: str, path: str, json_data: dict[str, Any] | None = None
178
+ ) -> Any:
179
+ """Send a mutating request to a direct API endpoint.
180
+
181
+ CSRF-exempt via the OCS-APIRequest header, exactly like the GETs — the
182
+ Mail app's write routes carry no ``@NoCSRFRequired``, so the header is
183
+ what makes them reachable with an app password.
184
+
185
+ Args:
186
+ method: ``POST``, ``PUT`` or ``DELETE``.
187
+ path: Path relative to :attr:`API_BASE` (e.g. ``/outbox``).
188
+ json_data: JSON body to send, or ``None`` for a bodyless call.
189
+
190
+ Returns:
191
+ The parsed JSON response body, or ``{}`` when there is no body.
192
+ """
193
+ # Only declare a JSON content type when there is actually a body: the
194
+ # tag assign/remove and delete routes take none, and announcing
195
+ # application/json for a bodyless request is misleading.
196
+ headers = dict(self._API_JSON_HEADERS)
197
+ if json_data is not None:
198
+ headers["Content-Type"] = "application/json"
199
+
200
+ response = await self._make_request(
201
+ method,
202
+ f"{self.API_BASE}{path}",
203
+ json=json_data,
204
+ headers=headers,
205
+ )
206
+ # ``_make_request`` (base) already raised on any non-2xx status. Several
207
+ # write routes legitimately return an empty body (setFlags returns a
208
+ # bare JSONResponse; the outbox send step can 204), so don't choke
209
+ # trying to JSON-decode nothing.
210
+ return response.json() if response.content else {}
211
+
212
+ # ------------------------------------------------------------------
213
+ # Public API methods
214
+ # ------------------------------------------------------------------
215
+
216
+ async def list_accounts(self) -> list[dict[str, Any]]:
217
+ """List all configured mail accounts.
218
+
219
+ Uses ``GET /index.php/apps/mail/api/accounts`` (direct resource route).
220
+
221
+ Returns:
222
+ List of raw account dicts. Mail 5.x keys the address as
223
+ ``emailAddress`` (the server layer maps it onto ``MailAccount.email``
224
+ via the field alias).
225
+ """
226
+ data = await self._api_get("/accounts")
227
+ return data if isinstance(data, list) else []
228
+
229
+ async def get_mailboxes(self, account_id: int) -> list[dict[str, Any]]:
230
+ """List mailboxes (folders) for a given account.
231
+
232
+ Uses ``GET /index.php/apps/mail/api/mailboxes?accountId=X``.
233
+
234
+ Mail 5.x wraps the folders in an account envelope —
235
+ ``{"id", "email", "mailboxes": [...], "delimiter"}`` — so the list is
236
+ nested under ``mailboxes`` rather than returned at the top level.
237
+
238
+ Args:
239
+ account_id: The account ID.
240
+
241
+ Returns:
242
+ List of mailbox dicts.
243
+ """
244
+ data = await self._api_get("/mailboxes", params={"accountId": account_id})
245
+ if isinstance(data, dict):
246
+ mailboxes = data.get("mailboxes", [])
247
+ return mailboxes if isinstance(mailboxes, list) else []
248
+ # Defensive: tolerate a bare list if a future/older version returns one.
249
+ return data if isinstance(data, list) else []
250
+
251
+ async def list_messages(
252
+ self,
253
+ mailbox_id: int,
254
+ *,
255
+ cursor: int | None = None,
256
+ search_filter: str | None = None,
257
+ limit: int = 20,
258
+ view: str | None = None,
259
+ ) -> list[dict[str, Any]]:
260
+ """List messages in a mailbox.
261
+
262
+ Uses ``GET /index.php/apps/mail/api/messages?mailboxId=X``.
263
+
264
+ Args:
265
+ mailbox_id: The mailbox database ID.
266
+ cursor: Pagination cursor (the ``databaseId`` of the last message
267
+ from the previous page).
268
+ search_filter: Optional search/filter string.
269
+ limit: Max messages to return (clamped to 1‑100).
270
+ view: ``"singleton"`` or ``"threaded"`` (default is threaded).
271
+
272
+ Returns:
273
+ List of message summary dicts.
274
+ """
275
+ params: dict[str, Any] = {
276
+ "mailboxId": mailbox_id,
277
+ "limit": min(max(1, limit), 100),
278
+ }
279
+ if cursor is not None:
280
+ params["cursor"] = cursor
281
+ if search_filter is not None:
282
+ params["filter"] = search_filter
283
+ if view is not None:
284
+ params["view"] = view
285
+
286
+ try:
287
+ data = await self._api_get("/messages", params=params)
288
+ except HTTPStatusError as e:
289
+ # Mail answers 400 (MailboxNotCachedException) for a mailbox it has
290
+ # never synced from IMAP. Background sync only covers INBOX, so
291
+ # subfolders stay uncached until opened in the web UI (GH #1636).
292
+ # Do what the UI does — run the initial sync — and retry once.
293
+ # 400 is overloaded (bad filter/cursor too), so match the exception
294
+ # type Mail's error middleware puts in the body.
295
+ if (
296
+ e.response.status_code != 400
297
+ or "MailboxNotCachedException" not in e.response.text
298
+ ):
299
+ raise
300
+ logger.debug("Mailbox %s not cached; running initial sync", mailbox_id)
301
+ await self.sync_mailbox(mailbox_id)
302
+ data = await self._api_get("/messages", params=params)
303
+ return data if isinstance(data, list) else []
304
+
305
+ async def sync_mailbox(self, mailbox_id: int, max_rounds: int = 20) -> None:
306
+ """Run Mail's initial IMAP→DB sync for a mailbox so it can be listed.
307
+
308
+ Uses ``POST /index.php/apps/mail/api/mailboxes/{id}/sync`` with
309
+ ``init=true``. A large mailbox is cached in chunks: Mail answers 202
310
+ until the initial sync completes, so repeat until it stops.
311
+
312
+ Args:
313
+ mailbox_id: The mailbox database ID.
314
+ max_rounds: Upper bound on 202 retries.
315
+ """
316
+ for _ in range(max_rounds):
317
+ response = await self._make_request(
318
+ "POST",
319
+ f"{self.API_BASE}/mailboxes/{mailbox_id}/sync",
320
+ json={"init": True},
321
+ headers=self._API_JSON_HEADERS,
322
+ )
323
+ if response.status_code != 202:
324
+ return
325
+ logger.warning(
326
+ "Initial sync of mailbox %s still incomplete after %d rounds",
327
+ mailbox_id,
328
+ max_rounds,
329
+ )
330
+
331
+ async def get_message(self, message_id: int) -> dict[str, Any]:
332
+ """Get a single message with full body content and metadata.
333
+
334
+ Uses the OCS route ``GET /ocs/v2.php/apps/mail/message/{id}``
335
+ which works with Basic Auth (App Password).
336
+
337
+ Args:
338
+ message_id: The message database ID.
339
+
340
+ Returns:
341
+ Full message dict with ``body``, ``attachments``, ``from``, ``to``,
342
+ ``subject``, ``flags``, etc.
343
+ """
344
+ data = await self._ocs_get(f"/message/{message_id}")
345
+ return data if isinstance(data, dict) else {}
346
+
347
+ async def download_attachment(
348
+ self, message_id: int, attachment_id: str
349
+ ) -> tuple[bytes, str, str]:
350
+ """Download an attachment's raw bytes from a message.
351
+
352
+ Uses the direct route
353
+ ``GET /index.php/apps/mail/api/messages/{id}/attachment/{id}``
354
+ (CSRF-exempt via the OCS-APIRequest header), which returns the raw file
355
+ bytes. The OCS ``/message/{id}/attachment/{id}`` route is unreliable
356
+ across Mail versions — on some setups it returns HTTP 200 with an empty,
357
+ non-JSON body (GH #989).
358
+
359
+ The ``attachment_id`` is URL‑encoded to prevent path traversal.
360
+
361
+ Args:
362
+ message_id: The message database ID.
363
+ attachment_id: The attachment ID string.
364
+
365
+ Returns:
366
+ ``(content, mime, name)``: the raw bytes, the MIME type without
367
+ parameters (``application/octet-stream`` when the response has
368
+ none), and the file name.
369
+ """
370
+ safe_id = quote(attachment_id, safe="")
371
+ # Binary download: unlike the JSON helpers, don't send
372
+ # ``Accept: application/json`` (mirrors ``DeckClient.get_attachment_file``).
373
+ # The client-wide ``OCS-APIRequest`` header still CSRF-exempts this route.
374
+ response = await self._make_request(
375
+ "GET",
376
+ f"{self.API_BASE}/messages/{message_id}/attachment/{safe_id}",
377
+ )
378
+ # ``_make_request`` (base) already raised on any non-2xx status.
379
+ ctype = (response.headers.get("content-type", "") or "").split(";")[0].strip()
380
+
381
+ # Recover the real filename from the Content-Disposition header (core's
382
+ # DownloadResponse sets ``attachment; filename="..."``); fall back to a
383
+ # synthetic name when the header is absent or has no filename.
384
+ name = (
385
+ self._filename_from_disposition(response.headers.get("content-disposition"))
386
+ or f"attachment_{message_id}_{attachment_id}"
387
+ )
388
+
389
+ return response.content, ctype or "application/octet-stream", name
390
+
391
+ async def get_attachment(
392
+ self, message_id: int, attachment_id: str
393
+ ) -> dict[str, Any]:
394
+ """Get an attachment's content from a message, base64-encoded.
395
+
396
+ See :meth:`download_attachment` for the route and the id encoding.
397
+
398
+ Args:
399
+ message_id: The message database ID.
400
+ attachment_id: The attachment ID string.
401
+
402
+ Returns:
403
+ Attachment dict with keys ``name``, ``mime``, ``size``, ``content``.
404
+ ``content`` is the raw attachment bytes base64-encoded.
405
+ """
406
+ raw, mime, name = await self.download_attachment(message_id, attachment_id)
407
+ return {
408
+ "name": name,
409
+ "mime": mime,
410
+ "size": len(raw),
411
+ "content": base64.b64encode(raw).decode("ascii"),
412
+ }
413
+
414
+ @staticmethod
415
+ def _filename_from_disposition(header: str | None) -> str | None:
416
+ """Extract the filename from a Content-Disposition header, if present.
417
+
418
+ Uses ``email.message.Message`` so quoted and RFC 2231-encoded filenames
419
+ are handled without the deprecated ``cgi`` module. Returns ``None`` when
420
+ the header is missing or carries no filename.
421
+ """
422
+ if not header:
423
+ return None
424
+ msg = Message()
425
+ msg["content-disposition"] = header
426
+ return msg.get_filename()
427
+
428
+ @staticmethod
429
+ def _local_message_payload(
430
+ account_id: int,
431
+ to: list[dict[str, str]],
432
+ subject: str,
433
+ body: str,
434
+ is_html: bool,
435
+ *,
436
+ cc: list[dict[str, str]] | None,
437
+ bcc: list[dict[str, str]] | None,
438
+ in_reply_to: str | None = None,
439
+ ai_generated: bool = False,
440
+ ) -> dict[str, Any]:
441
+ """Build the request body shared by ``POST /api/outbox`` and ``POST /api/drafts``.
442
+
443
+ Both routes create a Mail ``LocalMessage`` and take the same parameters
444
+ (``OutboxController::create`` / ``DraftsController::create``), so one
445
+ builder keeps the two from drifting apart. ``bodyPlain``/``bodyHtml``
446
+ exist since Mail 4.2.0; earlier versions took a single ``body``.
447
+ ``isAiGenerated`` exists since Mail 5.12.0 and is sent only for drafts
448
+ (``ai_generated``), so the outbox body stays as it was.
449
+ """
450
+ payload: dict[str, Any] = {
451
+ "accountId": account_id,
452
+ "subject": subject,
453
+ "isHtml": is_html,
454
+ "smimeSign": False,
455
+ "smimeEncrypt": False,
456
+ "to": to,
457
+ }
458
+ if is_html:
459
+ payload["bodyHtml"] = body
460
+ else:
461
+ payload["bodyPlain"] = body
462
+ if cc:
463
+ payload["cc"] = cc
464
+ if bcc:
465
+ payload["bcc"] = bcc
466
+ if in_reply_to:
467
+ payload["inReplyToMessageId"] = in_reply_to
468
+ if ai_generated:
469
+ payload["isAiGenerated"] = True
470
+ return payload
471
+
472
+ async def send_message(
473
+ self,
474
+ account_id: int,
475
+ to: list[dict[str, str]],
476
+ subject: str,
477
+ body: str,
478
+ is_html: bool = False,
479
+ cc: list[dict[str, str]] | None = None,
480
+ bcc: list[dict[str, str]] | None = None,
481
+ references: str | None = None,
482
+ ) -> dict[str, Any]:
483
+ """Send an email via the Mail 5.x outbox API.
484
+
485
+ Mail 5.x uses a two-step outbox flow (both CSRF-exempt via the
486
+ OCS-APIRequest header):
487
+ 1. POST ``/api/outbox`` to stage the message
488
+ 2. POST ``/api/outbox/{id}`` to send it
489
+
490
+ The ``From:`` identity is derived by the Mail app from ``account_id``
491
+ (``OutboxController::create`` has no from/email field), so it is not
492
+ sent here.
493
+
494
+ Args:
495
+ account_id: The mail account ID to send from.
496
+ to: List of recipients ``[{"label": "...", "email": "..."}]``.
497
+ subject: Subject line.
498
+ body: Message body (plain text or HTML depending on ``is_html``).
499
+ is_html: Whether ``body`` contains HTML.
500
+ cc: Optional CC recipients (same format as ``to``).
501
+ bcc: Optional BCC recipients (same format as ``to``).
502
+ references: Optional RFC 2822 ``Message-ID`` for reply threading.
503
+
504
+ Returns:
505
+ The response dict from the send step.
506
+ """
507
+ create_data = self._local_message_payload(
508
+ account_id,
509
+ to,
510
+ subject,
511
+ body,
512
+ is_html,
513
+ cc=cc,
514
+ bcc=bcc,
515
+ in_reply_to=references,
516
+ )
517
+
518
+ create_result = await self._api_write("POST", "/outbox", json_data=create_data)
519
+ outbox_id = create_result.get("data", {}).get("id")
520
+ if not outbox_id:
521
+ # Raise (don't return an error dict) so the server tool's
522
+ # ``except RequestError`` surfaces it — otherwise the discarded
523
+ # return value would let the tool report success on a covert failure.
524
+ raise RequestError(
525
+ f"Outbox create returned no id; response: {create_result!r}"
526
+ )
527
+
528
+ send_result = await self._api_write(
529
+ "POST", f"/outbox/{outbox_id}", json_data={}
530
+ )
531
+
532
+ return {
533
+ "success": True,
534
+ "message": "Message sent successfully",
535
+ "outbox_id": outbox_id,
536
+ "response": send_result,
537
+ }
538
+
539
+ async def create_draft(
540
+ self,
541
+ account_id: int,
542
+ to: list[dict[str, str]],
543
+ subject: str,
544
+ body: str,
545
+ is_html: bool = False,
546
+ cc: list[dict[str, str]] | None = None,
547
+ bcc: list[dict[str, str]] | None = None,
548
+ ) -> dict[str, Any]:
549
+ """Stage a draft in the Mail app's database. Never sends anything.
550
+
551
+ Uses ``POST /index.php/apps/mail/api/drafts`` (``DraftsController::create``,
552
+ Mail 2.2.0+), which answers 201 with the new ``LocalMessage`` wrapped in
553
+ ``data``. At this point the draft exists only in Nextcloud's database;
554
+ no mail client, including the Mail web UI, lists it until
555
+ :meth:`move_draft_to_imap` writes it to the account's Drafts mailbox.
556
+
557
+ No reply reference is sent. Mail would store ``inReplyToMessageId`` on
558
+ the local record, but writing the draft to IMAP does not turn it into
559
+ ``In-Reply-To``/``References`` headers, so the move drops it.
560
+
561
+ The draft is always marked as AI-generated (``isAiGenerated``): every
562
+ draft this client writes comes from an agent. Mail 5.12+ writes an
563
+ ``X-AI-Generated: 1`` header into the IMAP draft and shows the marker,
564
+ which the person sending can remove. Older versions ignore the field.
565
+
566
+ Args:
567
+ account_id: The mail account the draft belongs to.
568
+ to: Recipients ``[{"label": "...", "email": "..."}]`` (may be empty).
569
+ subject: Subject line.
570
+ body: Message body (plain text or HTML depending on ``is_html``).
571
+ is_html: Whether ``body`` contains HTML.
572
+ cc: Optional CC recipients (same format as ``to``).
573
+ bcc: Optional BCC recipients (same format as ``to``).
574
+
575
+ Returns:
576
+ The staged ``LocalMessage`` dict (``id``, ``accountId``, ``subject``, ...).
577
+
578
+ Raises:
579
+ RequestError: If the response carries no numeric draft id.
580
+ """
581
+ payload = self._local_message_payload(
582
+ account_id,
583
+ to,
584
+ subject,
585
+ body,
586
+ is_html,
587
+ cc=cc,
588
+ bcc=bcc,
589
+ ai_generated=True,
590
+ )
591
+ result = await self._api_write("POST", "/drafts", json_data=payload)
592
+ draft = result.get("data") if isinstance(result, dict) else None
593
+ if not isinstance(draft, dict) or not isinstance(draft.get("id"), int):
594
+ # Raise rather than return, for the same reason as send_message: the
595
+ # caller would otherwise go on to move a draft that does not exist.
596
+ raise RequestError(f"Draft create returned no id; response: {result!r}")
597
+ return draft
598
+
599
+ async def move_draft_to_imap(self, draft_id: int) -> dict[str, Any]:
600
+ """Write a staged draft to the account's IMAP Drafts mailbox.
601
+
602
+ Uses ``POST /index.php/apps/mail/api/drafts/move/{id}`` (Mail 3.3.0+),
603
+ bodyless, answering 202. Nothing is sent, even though the controller
604
+ calls ``DraftsService::sendMessage``: Mail APPENDs the message to the
605
+ Drafts mailbox with the ``\\Draft`` flag. An account without a Drafts
606
+ mailbox gets one named ``Drafts`` created on the spot.
607
+
608
+ On success Mail deletes the local record, so ``draft_id`` is stale
609
+ afterwards: update, delete and a second move all answer 404. On failure
610
+ Mail keeps the record but marks it ``failed``, which also excludes it
611
+ from Mail's own background move (``DraftsJob``).
612
+
613
+ Args:
614
+ draft_id: The staged draft's id from :meth:`create_draft`.
615
+
616
+ Returns:
617
+ The response body, ``{"status": "success", "data": "Message moved to IMAP"}``.
618
+ """
619
+ return await self._api_write("POST", f"/drafts/move/{draft_id}")
620
+
621
+ async def delete_local_draft(self, draft_id: int) -> None:
622
+ """Delete a draft that is still staged in the Mail app's database.
623
+
624
+ Uses ``DELETE /index.php/apps/mail/api/drafts/{id}``. This only reaches
625
+ the local record: it never touches IMAP, and it answers 404 once
626
+ :meth:`move_draft_to_imap` has succeeded.
627
+
628
+ Args:
629
+ draft_id: The staged draft's id from :meth:`create_draft`.
630
+ """
631
+ await self._api_write("DELETE", f"/drafts/{draft_id}")
632
+
633
+ async def save_draft(
634
+ self,
635
+ account_id: int,
636
+ to: list[dict[str, str]],
637
+ subject: str,
638
+ body: str,
639
+ is_html: bool = False,
640
+ cc: list[dict[str, str]] | None = None,
641
+ bcc: list[dict[str, str]] | None = None,
642
+ ) -> dict[str, Any]:
643
+ """Save a draft to the account's IMAP Drafts mailbox without sending it.
644
+
645
+ The same two steps the Mail web UI takes when its composer closes:
646
+ :meth:`create_draft` stages the draft, :meth:`move_draft_to_imap`
647
+ writes it to IMAP. Neither step sends anything.
648
+
649
+ If the move fails, the staged record is deleted before the error is
650
+ re-raised. Mail would keep it marked ``failed``, and since nothing lists
651
+ local drafts and the background move skips failed ones, it would be
652
+ orphaned in the database.
653
+
654
+ Args:
655
+ account_id: The mail account the draft belongs to.
656
+ to: Recipients ``[{"label": "...", "email": "..."}]`` (may be empty).
657
+ subject: Subject line.
658
+ body: Message body (plain text or HTML depending on ``is_html``).
659
+ is_html: Whether ``body`` contains HTML.
660
+ cc: Optional CC recipients (same format as ``to``).
661
+ bcc: Optional BCC recipients (same format as ``to``).
662
+
663
+ Returns:
664
+ ``{"draft", "response"}``: the staged ``LocalMessage`` dict, and the
665
+ move step's response body. The staged record's ``id`` is stale once
666
+ the move succeeds, since Mail deletes the record.
667
+ """
668
+ draft = await self.create_draft(
669
+ account_id,
670
+ to,
671
+ subject,
672
+ body,
673
+ is_html=is_html,
674
+ cc=cc,
675
+ bcc=bcc,
676
+ )
677
+ draft_id = draft["id"]
678
+ try:
679
+ move_result = await self.move_draft_to_imap(draft_id)
680
+ except (HTTPStatusError, RequestError):
681
+ await self._discard_staged_draft(draft_id)
682
+ raise
683
+ return {"draft": draft, "response": move_result}
684
+
685
+ async def _discard_staged_draft(self, draft_id: int) -> None:
686
+ """Best-effort removal of a staged draft after its move failed.
687
+
688
+ Fail-open on purpose: the move error is what the caller needs to see,
689
+ so a cleanup failure is logged instead of replacing it. A 404 here
690
+ usually means the move did complete and only its response was lost.
691
+ """
692
+ try:
693
+ await self.delete_local_draft(draft_id)
694
+ except (HTTPStatusError, RequestError) as e:
695
+ logger.warning(
696
+ "Could not discard staged mail draft %s after a failed move: %s",
697
+ draft_id,
698
+ e,
699
+ )
700
+
701
+ async def set_flags(self, message_id: int, flags: dict[str, bool]) -> None:
702
+ """Set IMAP flags on a message.
703
+
704
+ Uses ``PUT /index.php/apps/mail/api/messages/{id}/flags``. Note the body
705
+ shape: a *map* of flag name → bool, not a list of ``\\Seen``-style IMAP
706
+ flag names. Only the keys passed are touched; omitted flags are left
707
+ alone.
708
+
709
+ System flags (always applied): ``seen``, ``answered``, ``flagged``,
710
+ ``deleted``, ``draft``, ``recent``. Any other key is treated as a custom
711
+ IMAP keyword (e.g. ``$junk``) and is silently ignored by the server
712
+ unless the mailbox advertises it in ``PERMANENTFLAGS``.
713
+
714
+ Args:
715
+ message_id: The message database ID.
716
+ flags: Flag name → desired state.
717
+ """
718
+ await self._api_write(
719
+ "PUT", f"/messages/{message_id}/flags", json_data={"flags": flags}
720
+ )
721
+
722
+ async def ensure_tag(
723
+ self, display_name: str, color: str = DEFAULT_TAG_COLOR
724
+ ) -> dict[str, Any]:
725
+ """Create a mail tag, or return the existing one with that name.
726
+
727
+ Uses ``POST /index.php/apps/mail/api/tags``, which is idempotent:
728
+ ``MailManager::createTag`` derives the IMAP label from the display name
729
+ and returns the existing row when one matches. That matters because the
730
+ Mail app exposes **no** tag-listing route — this is the only way to
731
+ resolve a tag's per-user database ID.
732
+
733
+ Display names are normalised into the IMAP label as
734
+ ``'$' + lowercase(name with spaces as underscores)``, so ``"AI Index"``,
735
+ ``"ai index"`` and ``"ai_index"`` all resolve to the same tag.
736
+
737
+ Args:
738
+ display_name: Tag display name (max 128 characters).
739
+ color: Hex colour used only when the tag is created.
740
+
741
+ Returns:
742
+ The tag dict — ``{"id", "displayName", "imapLabel", "color", ...}``.
743
+ Note this route returns the bare tag, *not* wrapped in ``data`` the
744
+ way the outbox routes are.
745
+ """
746
+ tag = await self._api_write(
747
+ "POST", "/tags", json_data={"displayName": display_name, "color": color}
748
+ )
749
+ # Both callers depend on these: the id addresses the tag in a ``tags:``
750
+ # listing filter, the imapLabel addresses it in the assign/remove routes.
751
+ # Fail loudly here rather than KeyError-ing at the use site.
752
+ if not isinstance(tag, dict) or "id" not in tag or "imapLabel" not in tag:
753
+ raise RequestError(
754
+ f"Tag create returned an unusable tag for {display_name!r}: {tag!r}"
755
+ )
756
+ return tag
757
+
758
+ async def set_tag(self, message_id: int, imap_label: str) -> None:
759
+ """Assign an existing tag to a message.
760
+
761
+ Uses ``PUT /index.php/apps/mail/api/messages/{id}/tags/{imapLabel}``.
762
+ The label must already exist for this user (see :meth:`ensure_tag`); the
763
+ server answers 403 for an unknown one.
764
+
765
+ Args:
766
+ message_id: The message database ID.
767
+ imap_label: The tag's ``imapLabel`` (e.g. ``$vector_index``).
768
+ """
769
+ await self._api_write(
770
+ "PUT", f"/messages/{message_id}/tags/{quote(imap_label, safe='')}"
771
+ )
772
+
773
+ async def remove_tag(self, message_id: int, imap_label: str) -> None:
774
+ """Remove a tag from a message.
775
+
776
+ Uses ``DELETE /index.php/apps/mail/api/messages/{id}/tags/{imapLabel}``.
777
+
778
+ Args:
779
+ message_id: The message database ID.
780
+ imap_label: The tag's ``imapLabel``.
781
+ """
782
+ await self._api_write(
783
+ "DELETE", f"/messages/{message_id}/tags/{quote(imap_label, safe='')}"
784
+ )
785
+
786
+ async def move_message(self, message_id: int, destination_mailbox_id: int) -> None:
787
+ """Move a message to another mailbox.
788
+
789
+ Uses ``POST /index.php/apps/mail/api/messages/{id}/move``.
790
+
791
+ Args:
792
+ message_id: The message database ID.
793
+ destination_mailbox_id: Target mailbox database ID.
794
+ """
795
+ await self._api_write(
796
+ "POST",
797
+ f"/messages/{message_id}/move",
798
+ json_data={"destFolderId": destination_mailbox_id},
799
+ )
800
+
801
+ async def delete_message(self, message_id: int) -> None:
802
+ """Delete a message.
803
+
804
+ Uses ``DELETE /index.php/apps/mail/api/messages/{id}``. The Mail app
805
+ moves it to the account's trash mailbox, or expunges it outright when
806
+ the message is already in trash.
807
+
808
+ Args:
809
+ message_id: The message database ID.
810
+ """
811
+ await self._api_write("DELETE", f"/messages/{message_id}")
812
+
813
+ async def get_message_raw(self, message_id: int) -> str | None:
814
+ """Get the raw RFC 2822 source of a message.
815
+
816
+ Uses the OCS route ``GET /ocs/v2.php/apps/mail/message/{id}/raw``.
817
+
818
+ Args:
819
+ message_id: The message database ID.
820
+
821
+ Returns:
822
+ The raw email source string, or ``None`` if not found.
823
+ """
824
+ data = await self._ocs_get(f"/message/{message_id}/raw")
825
+ return data if isinstance(data, str) else None