1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! JMAP Mail — Email/* method implementations on SessionClient.
//!
//! Each method follows the standard five-step pattern:
//! 1. Validate arguments (defence-in-depth empty-state guards).
//! 2. Call `self.session_parts()?` → `(api_url, account_id)`.
//! 3. Build args JSON with `serde_json::json!({…})`.
//! 4. Call `build_request(method_name, args, USING_MAIL)`.
//! 5. Call `self.call_internal(api_url, &req).await?`.
//! 6. Call `jmap_base_client::extract_response(&resp, CALL_ID)?`.
use std::collections::HashMap;
use jmap_types::{Id, PatchObject, State};
use super::{
ChangesResponse, EmailCopyParams, EmailGetParams, EmailImportInput, EmailImportResponse,
EmailParseParams, EmailParseResponse, GetResponse, QueryChangesResponse, QueryResponse,
SetResponse,
};
impl super::SessionClient {
/// Fetch Email objects by IDs (RFC 8621 §4.1.8 — Email/get).
///
/// If `ids` is `None`, the server returns all Emails for the account.
/// Pass `properties: None` to return all fields.
/// Pass `params: None` to use server defaults for body-fetch options.
pub async fn email_get(
&self,
ids: Option<&[Id]>,
properties: Option<&[&str]>,
params: Option<EmailGetParams>,
) -> Result<GetResponse<jmap_mail_types::Email>, jmap_base_client::ClientError> {
let (api_url, account_id) = self.session_parts()?;
// Omit `ids` / `properties` entirely when None rather than sending
// an explicit JSON null. RFC 8620 §5.1 accepts both shapes, but the
// crate's other builders (set/changes/query) consistently use the
// conditional-add idiom; matching it here keeps the wire request
// canonical and avoids "present-but-null vs absent" interop quirks
// in proxies / audit loggers.
let mut args = serde_json::json!({ "accountId": account_id });
if let Some(id_slice) = ids {
args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
}
if let Some(props) = properties {
args["properties"] = serde_json::Value::Array(
props.iter().copied().map(serde_json::Value::from).collect(),
);
}
if let Some(p) = params {
let pv = serde_json::to_value(p).map_err(|e| {
jmap_base_client::ClientError::InvalidArgument(format!(
"email_get: failed to serialize params: {e}"
))
})?;
if let serde_json::Value::Object(map) = pv {
for (k, v) in map {
args[k] = v;
}
}
}
let req = super::build_request("Email/get", args, super::USING_MAIL);
let resp = self.call_internal(api_url, &req).await?;
jmap_base_client::extract_response(&resp, super::CALL_ID)
}
/// Fetch changes to Email objects since `since_state` (RFC 8621 §4.2 — Email/changes).
///
/// If `has_more_changes` is true in the response, call again with `new_state`
/// as `since_state` until the flag is false.
pub async fn email_changes(
&self,
since_state: &State,
max_changes: Option<u64>,
) -> Result<ChangesResponse, jmap_base_client::ClientError> {
// Defence-in-depth: see `thread_changes`.
if since_state.as_ref().is_empty() {
return Err(jmap_base_client::ClientError::InvalidArgument(
"email_changes: since_state may not be empty".into(),
));
}
let (api_url, account_id) = self.session_parts()?;
let mut args = serde_json::json!({
"accountId": account_id,
"sinceState": since_state,
});
if let Some(mc) = max_changes {
args["maxChanges"] = mc.into();
}
let req = super::build_request("Email/changes", args, super::USING_MAIL);
let resp = self.call_internal(api_url, &req).await?;
jmap_base_client::extract_response(&resp, super::CALL_ID)
}
/// Create, update, or destroy Email objects (RFC 8621 §4.3 — Email/set).
///
/// Pass `create`, `update`, and/or `destroy` as needed. All three are
/// optional; pass `None` to omit any operation from the request.
/// Pass `if_in_state: Some(&state)` to use an optimistic-concurrency guard.
///
/// `update` is `Option<HashMap<Id, PatchObject>>` (RFC 8620 §5.3). Wire
/// format is unchanged from a plain JSON object because [`PatchObject`]
/// is `#[serde(transparent)]`; the typed parameter binds the JSON Pointer
/// key + null-leaf removal contract to the type system.
pub async fn email_set(
&self,
create: Option<serde_json::Value>,
update: Option<HashMap<Id, PatchObject>>,
destroy: Option<Vec<Id>>,
if_in_state: Option<&State>,
) -> Result<SetResponse<jmap_mail_types::Email>, jmap_base_client::ClientError> {
let (api_url, account_id) = self.session_parts()?;
let mut args = serde_json::json!({
"accountId": account_id,
});
if let Some(s) = if_in_state {
args["ifInState"] = s.as_ref().into();
}
if let Some(c) = create {
args["create"] = c;
}
if let Some(u) = update {
args["update"] = serde_json::to_value(&u).map_err(|e| {
jmap_base_client::ClientError::InvalidArgument(format!(
"email_set: serializing update map failed: {e}"
))
})?;
}
if let Some(d) = destroy {
args["destroy"] = serde_json::to_value(&d).expect("Id Vec Serialize is infallible");
}
let req = super::build_request("Email/set", args, super::USING_MAIL);
let resp = self.call_internal(api_url, &req).await?;
jmap_base_client::extract_response(&resp, super::CALL_ID)
}
/// Query Email IDs with optional filter and sort (RFC 8621 §4.4 — Email/query).
///
/// Pass `filter: None` and `sort: None` to return all Emails with
/// server-default ordering. Use `position` and `limit` for pagination.
/// Pass `collapse_threads: Some(true)` to return at most one email per thread.
pub async fn email_query(
&self,
filter: Option<serde_json::Value>,
sort: Option<serde_json::Value>,
position: Option<u64>,
limit: Option<u64>,
collapse_threads: Option<bool>,
) -> Result<QueryResponse, jmap_base_client::ClientError> {
let (api_url, account_id) = self.session_parts()?;
let mut args = serde_json::json!({
"accountId": account_id,
});
if let Some(f) = filter {
args["filter"] = f;
}
if let Some(s) = sort {
args["sort"] = s;
}
if let Some(p) = position {
args["position"] = p.into();
}
if let Some(l) = limit {
args["limit"] = l.into();
}
if let Some(ct) = collapse_threads {
args["collapseThreads"] = ct.into();
}
let req = super::build_request("Email/query", args, super::USING_MAIL);
let resp = self.call_internal(api_url, &req).await?;
jmap_base_client::extract_response(&resp, super::CALL_ID)
}
/// Fetch query-result changes for Email since `since_query_state`
/// (RFC 8621 §4.5 — Email/queryChanges).
pub async fn email_query_changes(
&self,
since_query_state: &State,
max_changes: Option<u64>,
collapse_threads: Option<bool>,
) -> Result<QueryChangesResponse, jmap_base_client::ClientError> {
// Defence-in-depth: see `thread_changes`.
if since_query_state.as_ref().is_empty() {
return Err(jmap_base_client::ClientError::InvalidArgument(
"email_query_changes: since_query_state may not be empty".into(),
));
}
let (api_url, account_id) = self.session_parts()?;
let mut args = serde_json::json!({
"accountId": account_id,
"sinceQueryState": since_query_state,
});
if let Some(mc) = max_changes {
args["maxChanges"] = mc.into();
}
if let Some(ct) = collapse_threads {
args["collapseThreads"] = ct.into();
}
let req = super::build_request("Email/queryChanges", args, super::USING_MAIL);
let resp = self.call_internal(api_url, &req).await?;
jmap_base_client::extract_response(&resp, super::CALL_ID)
}
/// Copy Emails from another account (RFC 8621 §4.7 — Email/copy).
///
/// `params` carries `fromAccountId` and optional destroy-after-copy flags.
/// `create` is a map of creation keys to partial Email objects (with new
/// mailboxIds etc.) as described in RFC 8621 §4.7.
pub async fn email_copy(
&self,
params: EmailCopyParams,
create: serde_json::Value,
) -> Result<SetResponse<jmap_mail_types::Email>, jmap_base_client::ClientError> {
let (api_url, account_id) = self.session_parts()?;
let mut args = serde_json::json!({
"accountId": account_id,
"fromAccountId": params.from_account_id,
"create": create,
});
if let Some(v) = params.on_success_destroy_original {
args["onSuccessDestroyOriginal"] = v.into();
}
if let Some(v) = params.destroy_from_if_in_state {
args["destroyFromIfInState"] = v.as_ref().into();
}
let req = super::build_request("Email/copy", args, super::USING_MAIL);
let resp = self.call_internal(api_url, &req).await?;
jmap_base_client::extract_response(&resp, super::CALL_ID)
}
/// Import raw RFC 5322 messages into the account (RFC 8621 §4.8 — Email/import).
///
/// Each entry in `emails` maps a caller-chosen creation id to an
/// [`EmailImportInput`] referencing a previously uploaded blob and the
/// target mailbox(es). The blob must have been uploaded via the standard
/// blob-upload mechanism on `jmap-base-client` before calling this method.
///
/// At least one mailbox id is required per RFC 8621 §4.8; the empty-set
/// case is rejected client-side as `InvalidArgument`. An empty `emails`
/// map is also rejected — a no-op import is never useful and would
/// generate a round-trip with no successful creations.
///
/// Pass `if_in_state: Some(&state)` for an optimistic-concurrency guard
/// against the Email object state (RFC 8621 §4.8 returns `stateMismatch`
/// if the supplied state does not match).
///
/// Per-creation failures appear in [`EmailImportResponse::not_created`]
/// as [`super::SetError`] values; possible error codes include `alreadyExists`
/// (with an `existingId` extra field), `invalidProperties`, `overQuota`,
/// and `invalidEmail`.
pub async fn email_import(
&self,
emails: &HashMap<String, EmailImportInput<'_>>,
if_in_state: Option<&State>,
) -> Result<EmailImportResponse, jmap_base_client::ClientError> {
if emails.is_empty() {
return Err(jmap_base_client::ClientError::InvalidArgument(
"email_import: emails map may not be empty".into(),
));
}
for (key, input) in emails {
if input.mailbox_ids.is_empty() {
return Err(jmap_base_client::ClientError::InvalidArgument(format!(
"email_import: mailboxIds for creation id '{key}' may not be empty (RFC 8621 §4.8)"
)));
}
}
let (api_url, account_id) = self.session_parts()?;
let emails_value = serde_json::to_value(emails).map_err(|e| {
jmap_base_client::ClientError::InvalidArgument(format!(
"email_import: serializing emails map failed: {e}"
))
})?;
let mut args = serde_json::json!({
"accountId": account_id,
"emails": emails_value,
});
if let Some(s) = if_in_state {
args["ifInState"] = s.as_ref().into();
}
let req = super::build_request("Email/import", args, super::USING_MAIL);
let resp = self.call_internal(api_url, &req).await?;
jmap_base_client::extract_response(&resp, super::CALL_ID)
}
/// Parse uploaded blobs as RFC 5322 messages without importing them
/// (RFC 8621 §4.9 — Email/parse).
///
/// Returns Email objects derived from each blob. Per RFC 8621 §4.9 the
/// returned Emails have `id`, `mailboxIds`, `keywords`, and `receivedAt`
/// set to `null` (the messages are not in the mail store); `threadId`
/// MAY be present if the server can predict the assignment.
///
/// Pass `params: None` to use server defaults for properties and body
/// fetching. The set of properties returned defaults to the spec-listed
/// header/body fields documented in RFC 8621 §4.9.
///
/// Empty `blob_ids` is rejected as `InvalidArgument` — a no-op parse
/// round-trip is never useful.
pub async fn email_parse(
&self,
blob_ids: &[Id],
params: Option<EmailParseParams>,
) -> Result<EmailParseResponse, jmap_base_client::ClientError> {
if blob_ids.is_empty() {
return Err(jmap_base_client::ClientError::InvalidArgument(
"email_parse: blob_ids may not be empty".into(),
));
}
let (api_url, account_id) = self.session_parts()?;
let mut args = serde_json::json!({
"accountId": account_id,
"blobIds": blob_ids,
});
if let Some(p) = params {
let pv = serde_json::to_value(&p).map_err(|e| {
jmap_base_client::ClientError::InvalidArgument(format!(
"email_parse: failed to serialize params: {e}"
))
})?;
if let serde_json::Value::Object(map) = pv {
for (k, v) in map {
args[k] = v;
}
}
}
let req = super::build_request("Email/parse", args, super::USING_MAIL);
let resp = self.call_internal(api_url, &req).await?;
jmap_base_client::extract_response(&resp, super::CALL_ID)
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use serde_json::json;
// email_get_empty_id_returns_invalid_argument was deleted in JMAP-6by7.2
// (typed-Id refactor): under `Option<&[Id]>` the empty-Id case becomes
// impossible to express through the typed API.
// The InvalidArgument guards for empty since_state and since_query_state
// live in email_changes / email_query_changes production code; testing them
// requires a wiremock-backed async harness. See JMAP-sc1b.64.
// Deleted in JMAP-tco1.5 as Pattern E (vacuous inline tests):
// - email_get_request_shape
// - email_changes_request_includes_since_state
// - email_set_destroy_request_shape
// - email_copy_request_shape
// - email_query_request_shape
// Each hand-built `args = json!({...})` and fed it to `build_request`,
// never invoking the `email_get` / `email_changes` / `email_set` /
// `email_copy` / `email_query` production builders. Real production-path
// coverage for these methods is tracked as a wiremock-smoke gap under
// JMAP-uuoi (no `tests/email_*.rs` smoke files exist yet).
//
// `build_request`, `CALL_ID`, and `USING_MAIL` themselves have their
// own focused tests in `methods/mod.rs`.
/// Oracle: Email deserialization from RFC 8621 §4 example JSON subset.
/// Only fields present in the fixture are checked; Email has many optional fields.
#[test]
fn email_get_response_deserializes() {
let json = json!({
"accountId": "acc1",
"state": "s10",
"list": [
{
"id": "e1",
"blobId": "b1",
"threadId": "t1",
"mailboxIds": { "mb1": true },
"keywords": { "$seen": true },
"size": 1024,
"receivedAt": "2024-01-01T00:00:00Z"
}
],
"notFound": []
});
use super::super::GetResponse;
let resp: GetResponse<jmap_mail_types::Email> =
serde_json::from_value(json).expect("must deserialize Email GetResponse");
assert_eq!(resp.list.len(), 1);
assert_eq!(resp.list[0].id.as_ref(), "e1");
}
}