missive 0.6.2

Compose, deliver, preview, and test emails in Rust - pluggable providers with zero configuration code
Documentation
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! JMAP provider for sending emails via JMAP-compliant servers.
//!
//! This is a minimal JMAP client implementation for email submission only.
//! It works with any JMAP-compliant server including:
//!
//! - [Stalwart Mail Server](https://stalw.art/)
//! - [Fastmail](https://www.fastmail.com/)
//! - [Cyrus IMAP](https://www.cyrusimap.org/)
//!
//! # How It Works
//!
//! JMAP (JSON Meta Application Protocol) is a modern, stateless alternative
//! to IMAP/SMTP that uses JSON over HTTP. Sending an email requires:
//!
//! 1. Session discovery (GET `/.well-known/jmap`)
//! 2. Fetch the drafts mailbox ID (`Mailbox/get`)
//! 3. Create email in drafts (`Email/set`)
//! 4. Submit for delivery (`EmailSubmission/set`)
//!
//! This provider handles all steps in a single `deliver()` call.
//!
//! # JMAP Submission Workflow
//!
//! Per [RFC 8621 Section 4](https://www.rfc-editor.org/rfc/rfc8621#section-4),
//! emails in JMAP must belong to at least one mailbox at all times. This
//! provider follows the standard submission pattern:
//!
//! 1. Create the email in the user's drafts mailbox
//! 2. Submit via `EmailSubmission/set` with `onSuccessDestroyEmail`
//! 3. The server automatically deletes the draft after successful delivery
//!
//! This ensures spec compliance across all JMAP servers.
//!
//! # Example
//!
//! ```rust,ignore
//! use missive::providers::JmapMailer;
//!
//! // Basic auth
//! let mailer = JmapMailer::new("https://jmap.example.com")
//!     .credentials("username", "password")
//!     .build();
//!
//! // Bearer token (OAuth2)
//! let mailer = JmapMailer::new("https://jmap.example.com")
//!     .bearer_token("your-oauth-token")
//!     .build();
//! ```
//!
//! # Environment Variables
//!
//! ```bash
//! EMAIL_PROVIDER=jmap
//! JMAP_URL=https://jmap.example.com
//! JMAP_USERNAME=your-username
//! JMAP_PASSWORD=your-password
//! # Or use bearer token instead:
//! # JMAP_BEARER_TOKEN=your-oauth-token
//! ```

use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;

use crate::email::Email;
use crate::error::MailError;
use crate::mailer::{DeliveryResult, Mailer};

/// JMAP email provider.
///
/// A minimal JMAP client for email submission. Works with any
/// JMAP-compliant server (Stalwart, Fastmail, Cyrus, etc.).
pub struct JmapMailer {
    session_url: String,
    auth: JmapAuth,
    client: Client,
    /// Cached session data (API URL, account ID, identity ID)
    session: parking_lot::RwLock<Option<JmapSession>>,
}

#[derive(Clone)]
enum JmapAuth {
    Basic { username: String, password: String },
    Bearer { token: String },
}

#[derive(Clone)]
struct JmapSession {
    api_url: String,
    account_id: String,
    identity_id: Option<String>,
    drafts_mailbox_id: Option<String>,
}

impl JmapMailer {
    /// Create a new JMAP mailer builder.
    ///
    /// The URL should be either:
    /// - The JMAP session URL directly (e.g., `https://jmap.example.com/session`)
    /// - The server base URL (will append `/.well-known/jmap`)
    #[allow(clippy::new_ret_no_self)]
    pub fn new(url: &str) -> JmapBuilder {
        // Normalize URL to session endpoint
        let session_url = if url.ends_with("/session") || url.contains("/.well-known/jmap") {
            url.to_string()
        } else {
            format!("{}/.well-known/jmap", url.trim_end_matches('/'))
        };

        JmapBuilder {
            session_url,
            auth: None,
            client: None,
            test_session: None,
        }
    }

    /// Fetch or return cached JMAP session.
    async fn get_session(&self) -> Result<JmapSession, MailError> {
        // Check cache first
        {
            let guard = self.session.read();
            if let Some(ref session) = *guard {
                return Ok(session.clone());
            }
        }

        // Fetch session
        let session = self.fetch_session().await?;

        // Cache it
        {
            let mut guard = self.session.write();
            *guard = Some(session.clone());
        }

        Ok(session)
    }

    /// Fetch JMAP session from server.
    async fn fetch_session(&self) -> Result<JmapSession, MailError> {
        let req = self.apply_auth(self.client.get(&self.session_url));
        let response = req.send().await?;

        if !response.status().is_success() {
            return Err(MailError::provider_with_status(
                "jmap",
                format!("Session discovery failed: {}", response.status()),
                response.status().as_u16(),
            ));
        }

        let session: JmapSessionResponse = response.json().await?;

        // Get the primary account ID
        let account_id = session
            .primary_accounts
            .get("urn:ietf:params:jmap:mail")
            .or_else(|| {
                session
                    .primary_accounts
                    .get("urn:ietf:params:jmap:submission")
            })
            .or_else(|| session.accounts.keys().next())
            .ok_or_else(|| MailError::Configuration("No JMAP mail account found".into()))?
            .clone();

        // Try to find an identity ID for submission
        let identity_id = None; // Will be fetched on first send if needed

        Ok(JmapSession {
            api_url: session.api_url,
            account_id,
            identity_id,
            drafts_mailbox_id: None, // Will be fetched on first send
        })
    }

    /// Apply authentication to a request.
    fn apply_auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        match &self.auth {
            JmapAuth::Basic { username, password } => req.basic_auth(username, Some(password)),
            JmapAuth::Bearer { token } => req.bearer_auth(token),
        }
    }

    /// Fetch identity ID if not cached.
    async fn get_identity_id(&self, session: &JmapSession) -> Result<String, MailError> {
        if let Some(ref id) = session.identity_id {
            return Ok(id.clone());
        }

        // Fetch identities from server
        let request = JmapRequest {
            using: vec![
                "urn:ietf:params:jmap:core".into(),
                "urn:ietf:params:jmap:submission".into(),
            ],
            method_calls: vec![(
                "Identity/get".into(),
                json!({
                    "accountId": session.account_id,
                }),
                "i0".into(),
            )],
        };

        let req = self.apply_auth(self.client.post(&session.api_url));
        let response = req
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await?;

        if !response.status().is_success() {
            // Fall back to using account ID as identity
            return Ok(session.account_id.clone());
        }

        let jmap_response: JmapResponse = response.json().await?;

        // Extract identity ID from response
        for (method, result, _) in jmap_response.method_responses {
            if method == "Identity/get" {
                if let Some(list) = result.get("list").and_then(|l| l.as_array()) {
                    if let Some(first) = list.first() {
                        if let Some(id) = first.get("id").and_then(|i| i.as_str()) {
                            return Ok(id.to_string());
                        }
                    }
                }
            }
        }

        // Fall back to account ID
        Ok(session.account_id.clone())
    }

    /// Fetch drafts mailbox ID if not cached.
    ///
    /// Per RFC 8621, emails must belong to at least one mailbox. We use the
    /// drafts mailbox for outgoing emails, falling back to inbox if drafts
    /// doesn't exist. The email is automatically destroyed after successful
    /// submission via `onSuccessDestroyEmail`.
    async fn get_drafts_mailbox_id(&self, session: &JmapSession) -> Result<String, MailError> {
        if let Some(ref id) = session.drafts_mailbox_id {
            return Ok(id.clone());
        }

        // Fetch mailboxes from server
        let request = JmapRequest {
            using: vec![
                "urn:ietf:params:jmap:core".into(),
                "urn:ietf:params:jmap:mail".into(),
            ],
            method_calls: vec![(
                "Mailbox/get".into(),
                json!({
                    "accountId": session.account_id,
                }),
                "m0".into(),
            )],
        };

        let req = self.apply_auth(self.client.post(&session.api_url));
        let response = req
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(MailError::provider_with_status(
                "jmap",
                "Failed to fetch mailboxes",
                response.status().as_u16(),
            ));
        }

        let jmap_response: JmapResponse = response.json().await?;

        // Find drafts mailbox (role = "drafts") or fall back to first mailbox
        for (method, result, _) in jmap_response.method_responses {
            if method == "Mailbox/get" {
                if let Some(list) = result.get("list").and_then(|l| l.as_array()) {
                    // First try to find drafts
                    for mailbox in list {
                        if mailbox.get("role").and_then(|r| r.as_str()) == Some("drafts") {
                            if let Some(id) = mailbox.get("id").and_then(|i| i.as_str()) {
                                return Ok(id.to_string());
                            }
                        }
                    }
                    // Fall back to inbox
                    for mailbox in list {
                        if mailbox.get("role").and_then(|r| r.as_str()) == Some("inbox") {
                            if let Some(id) = mailbox.get("id").and_then(|i| i.as_str()) {
                                return Ok(id.to_string());
                            }
                        }
                    }
                    // Fall back to first mailbox
                    if let Some(first) = list.first() {
                        if let Some(id) = first.get("id").and_then(|i| i.as_str()) {
                            return Ok(id.to_string());
                        }
                    }
                }
            }
        }

        Err(MailError::Configuration("No mailboxes found".into()))
    }

    /// Build the JMAP Email object from our Email struct.
    fn build_email_object(&self, email: &Email, mailbox_id: &str) -> Result<Value, MailError> {
        let from = email.from.as_ref().ok_or(MailError::MissingField("from"))?;

        if email.to.is_empty() {
            return Err(MailError::MissingField("to"));
        }

        // Build address objects
        let from_addrs: Vec<Value> = vec![json!({
            "name": from.name,
            "email": from.email,
        })];

        let to_addrs: Vec<Value> = email
            .to
            .iter()
            .map(|a| {
                json!({
                    "name": a.name,
                    "email": a.email,
                })
            })
            .collect();

        let cc_addrs: Option<Vec<Value>> = if email.cc.is_empty() {
            None
        } else {
            Some(
                email
                    .cc
                    .iter()
                    .map(|a| {
                        json!({
                            "name": a.name,
                            "email": a.email,
                        })
                    })
                    .collect(),
            )
        };

        let bcc_addrs: Option<Vec<Value>> = if email.bcc.is_empty() {
            None
        } else {
            Some(
                email
                    .bcc
                    .iter()
                    .map(|a| {
                        json!({
                            "name": a.name,
                            "email": a.email,
                        })
                    })
                    .collect(),
            )
        };

        let reply_to: Option<Vec<Value>> = if email.reply_to.is_empty() {
            None
        } else {
            Some(
                email
                    .reply_to
                    .iter()
                    .map(|a| {
                        json!({
                            "name": a.name,
                            "email": a.email,
                        })
                    })
                    .collect(),
            )
        };

        // Build body parts
        let mut body_values: HashMap<String, Value> = HashMap::new();
        let mut text_body: Vec<Value> = vec![];
        let mut html_body: Vec<Value> = vec![];

        if let Some(ref text) = email.text_body {
            body_values.insert(
                "text".into(),
                json!({
                    "value": text,
                    "isEncodingProblem": false,
                    "isTruncated": false,
                }),
            );
            text_body.push(json!({
                "partId": "text",
                "type": "text/plain",
            }));
        }

        if let Some(ref html) = email.html_body {
            body_values.insert(
                "html".into(),
                json!({
                    "value": html,
                    "isEncodingProblem": false,
                    "isTruncated": false,
                }),
            );
            html_body.push(json!({
                "partId": "html",
                "type": "text/html",
            }));
        }

        // Build attachments
        let attachments: Option<Vec<Value>> = if email.attachments.is_empty() {
            None
        } else {
            Some(
                email
                    .attachments
                    .iter()
                    .enumerate()
                    .map(|(i, a)| {
                        let part_id = format!("att{}", i);
                        body_values.insert(
                            part_id.clone(),
                            json!({
                                "value": a.base64_data(),
                                "isEncodingProblem": false,
                                "isTruncated": false,
                            }),
                        );
                        let mut att = json!({
                            "partId": part_id,
                            "type": a.content_type,
                            "name": a.filename,
                            "disposition": if a.is_inline() { "inline" } else { "attachment" },
                        });
                        if let Some(ref cid) = a.content_id {
                            att["cid"] = json!(cid);
                        }
                        att
                    })
                    .collect(),
            )
        };

        // Build custom headers
        let headers: Option<Vec<Value>> = if email.headers.is_empty() {
            None
        } else {
            Some(
                email
                    .headers
                    .iter()
                    .map(|(k, v)| {
                        json!({
                            "name": k,
                            "value": v,
                        })
                    })
                    .collect(),
            )
        };

        let mut email_obj = json!({
            "mailboxIds": { mailbox_id: true },
            "from": from_addrs,
            "to": to_addrs,
            "subject": email.subject,
            "bodyValues": body_values,
        });

        // Add optional fields
        if !text_body.is_empty() {
            email_obj["textBody"] = json!(text_body);
        }
        if !html_body.is_empty() {
            email_obj["htmlBody"] = json!(html_body);
        }
        if let Some(cc) = cc_addrs {
            email_obj["cc"] = json!(cc);
        }
        if let Some(bcc) = bcc_addrs {
            email_obj["bcc"] = json!(bcc);
        }
        if let Some(rt) = reply_to {
            email_obj["replyTo"] = json!(rt);
        }
        if let Some(atts) = attachments {
            email_obj["attachments"] = json!(atts);
        }
        if let Some(hdrs) = headers {
            email_obj["headers"] = json!(hdrs);
        }

        // Mark for sending without saving to mailbox
        email_obj["keywords"] = json!({ "$draft": true });

        Ok(email_obj)
    }
}

/// Builder for JmapMailer.
pub struct JmapBuilder {
    session_url: String,
    auth: Option<JmapAuth>,
    client: Option<Client>,
    /// Pre-configured session for testing (bypasses session discovery)
    test_session: Option<(String, String, Option<String>)>, // (api_url, account_id, drafts_mailbox_id)
}

impl JmapBuilder {
    /// Set basic authentication credentials.
    pub fn credentials(mut self, username: &str, password: &str) -> Self {
        self.auth = Some(JmapAuth::Basic {
            username: username.to_string(),
            password: password.to_string(),
        });
        self
    }

    /// Set bearer token authentication (OAuth2).
    pub fn bearer_token(mut self, token: &str) -> Self {
        self.auth = Some(JmapAuth::Bearer {
            token: token.to_string(),
        });
        self
    }

    /// Use a custom reqwest client.
    pub fn client(mut self, client: Client) -> Self {
        self.client = Some(client);
        self
    }

    /// Set a pre-configured session for testing (bypasses session discovery).
    ///
    /// This is useful for unit tests where you want to mock the JMAP API
    /// without needing to mock the session discovery endpoint.
    #[doc(hidden)]
    pub fn test_session(mut self, api_url: &str, account_id: &str) -> Self {
        self.test_session = Some((api_url.to_string(), account_id.to_string(), None));
        self
    }

    /// Set a pre-configured session with drafts mailbox for testing.
    #[doc(hidden)]
    pub fn test_session_with_mailbox(
        mut self,
        api_url: &str,
        account_id: &str,
        drafts_mailbox_id: &str,
    ) -> Self {
        self.test_session = Some((
            api_url.to_string(),
            account_id.to_string(),
            Some(drafts_mailbox_id.to_string()),
        ));
        self
    }

    /// Build the JmapMailer.
    pub fn build(self) -> JmapMailer {
        // If test_session is provided, pre-populate the session cache
        let session = self
            .test_session
            .map(|(api_url, account_id, drafts_mailbox_id)| JmapSession {
                api_url,
                account_id,
                identity_id: Some("default".to_string()),
                drafts_mailbox_id,
            });

        JmapMailer {
            session_url: self.session_url,
            auth: self.auth.unwrap_or(JmapAuth::Basic {
                username: String::new(),
                password: String::new(),
            }),
            client: self.client.unwrap_or_default(),
            session: parking_lot::RwLock::new(session),
        }
    }
}

#[async_trait]
impl Mailer for JmapMailer {
    async fn deliver(&self, email: &Email) -> Result<DeliveryResult, MailError> {
        // Get session info
        let session = self.get_session().await?;
        let identity_id = self.get_identity_id(&session).await?;
        let mailbox_id = self.get_drafts_mailbox_id(&session).await?;

        // Build email object
        let email_obj = self.build_email_object(email, &mailbox_id)?;

        // Build JMAP request with Email/set and EmailSubmission/set
        let request = JmapRequest {
            using: vec![
                "urn:ietf:params:jmap:core".into(),
                "urn:ietf:params:jmap:mail".into(),
                "urn:ietf:params:jmap:submission".into(),
            ],
            method_calls: vec![
                // First create the email
                (
                    "Email/set".into(),
                    json!({
                        "accountId": session.account_id,
                        "create": {
                            "draft": email_obj,
                        },
                    }),
                    "e0".into(),
                ),
                // Then submit it for delivery
                (
                    "EmailSubmission/set".into(),
                    json!({
                        "accountId": session.account_id,
                        "create": {
                            "sub": {
                                "emailId": "#draft",
                                "identityId": identity_id,
                            },
                        },
                        "onSuccessDestroyEmail": ["#sub"],
                    }),
                    "s0".into(),
                ),
            ],
        };

        // Send request
        let req = self.apply_auth(self.client.post(&session.api_url));
        let response = req
            .header("Content-Type", "application/json")
            .header("User-Agent", format!("missive/{}", crate::VERSION))
            .json(&request)
            .send()
            .await?;

        let status = response.status();

        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(MailError::provider_with_status(
                "jmap",
                format!("JMAP request failed: {}", error_text),
                status.as_u16(),
            ));
        }

        let jmap_response: JmapResponse = response.json().await?;

        // Check for errors in method responses
        for (method, result, _) in &jmap_response.method_responses {
            if method == "error" {
                let error_type = result
                    .get("type")
                    .and_then(|t| t.as_str())
                    .unwrap_or("unknown");
                let description = result
                    .get("description")
                    .and_then(|d| d.as_str())
                    .unwrap_or("Unknown error");
                return Err(MailError::ProviderError {
                    provider: "jmap",
                    message: format!("{}: {}", error_type, description),
                    status: None,
                });
            }

            // Check for Email/set or EmailSubmission/set errors
            if method == "Email/set" || method == "EmailSubmission/set" {
                if let Some(not_created) = result.get("notCreated") {
                    if let Some(obj) = not_created.as_object() {
                        if let Some((_, error)) = obj.into_iter().next() {
                            let error_type = error
                                .get("type")
                                .and_then(|t| t.as_str())
                                .unwrap_or("unknown");
                            let description = error
                                .get("description")
                                .and_then(|d| d.as_str())
                                .unwrap_or("Creation failed");
                            return Err(MailError::ProviderError {
                                provider: "jmap",
                                message: format!("{}: {}", error_type, description),
                                status: None,
                            });
                        }
                    }
                }
            }
        }

        // Extract submission ID from response
        let mut submission_id = uuid::Uuid::new_v4().to_string();
        for (method, result, _) in &jmap_response.method_responses {
            if method == "EmailSubmission/set" {
                if let Some(created) = result.get("created") {
                    if let Some(sub) = created.get("sub") {
                        if let Some(id) = sub.get("id").and_then(|i| i.as_str()) {
                            submission_id = id.to_string();
                        }
                    }
                }
            }
        }

        Ok(DeliveryResult::with_response(
            submission_id,
            json!({ "provider": "jmap" }),
        ))
    }

    fn provider_name(&self) -> &'static str {
        "jmap"
    }
}

// ============================================================================
// JMAP Protocol Types
// ============================================================================

#[derive(Debug, Serialize)]
struct JmapRequest {
    using: Vec<String>,
    #[serde(rename = "methodCalls")]
    method_calls: Vec<(String, Value, String)>,
}

#[derive(Debug, Deserialize)]
struct JmapResponse {
    #[serde(rename = "methodResponses")]
    method_responses: Vec<(String, Value, String)>,
}

#[derive(Debug, Deserialize)]
struct JmapSessionResponse {
    #[serde(rename = "apiUrl")]
    api_url: String,
    accounts: HashMap<String, Value>,
    #[serde(rename = "primaryAccounts", default)]
    primary_accounts: HashMap<String, String>,
}