agentmail-rs 0.1.0

Unofficial typed Rust client for AgentMail (agentmail.to), the email API for agents.
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
//! Unofficial typed Rust client for [AgentMail](https://agentmail.to), the
//! email API for agents (official SDKs exist for Python and TypeScript; this
//! fills the Rust gap).
//!
//! Wire shapes follow AgentMail's OpenAPI spec (`docs.agentmail.to/openapi.json`,
//! API v0). Coverage focuses on the transactional core: inboxes, messages
//! (send/list/get), and webhooks. Everything deserializes permissively -
//! unknown fields are ignored, optional fields default, so spec additions
//! don't break callers.
//!
//! ```no_run
//! # async fn demo() -> Result<(), agentmail::Error> {
//! let client = agentmail::Client::from_env()?; // AGENTMAIL_API_KEY
//! let inbox = client
//!     .create_inbox(agentmail::CreateInbox {
//!         username: Some("my-agent".into()),
//!         display_name: Some("My Agent".into()),
//!         ..Default::default()
//!     })
//!     .await?;
//! client
//!     .send_message(
//!         &inbox.inbox_id,
//!         agentmail::SendMessage {
//!             to: vec!["someone@example.com".into()],
//!             subject: Some("Hello".into()),
//!             text: Some("From an agent's own inbox.".into()),
//!             ..Default::default()
//!         },
//!     )
//!     .await?;
//! # Ok(()) }
//! ```

#![warn(missing_docs)]

use serde::{Deserialize, Serialize};

/// The production API host. Override with `Client::new(key, base_url)` for
/// the EU region (`https://api.agentmail.eu`) or a mock server.
pub const DEFAULT_BASE_URL: &str = "https://api.agentmail.to";

/// The per-request timeout applied by [`Client::new`] (connect + response).
pub const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Everything that can go wrong talking to AgentMail.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// [`Client::from_env`] found no `AGENTMAIL_API_KEY`.
    #[error("AGENTMAIL_API_KEY is not set")]
    MissingApiKey,
    /// The request never completed: DNS, TLS, connect, or the
    /// [`DEFAULT_TIMEOUT`] elapsed.
    #[error("transport error: {0}")]
    Transport(#[from] reqwest::Error),
    /// A non-2xx answer from the API, with whatever body it sent.
    #[error("AgentMail answered {status}: {body}")]
    Api {
        /// The HTTP status the API answered with.
        status: reqwest::StatusCode,
        /// The response body, verbatim (AgentMail sends JSON error details).
        body: String,
    },
    /// A 2xx answer whose body didn't decode into the expected type - either
    /// a bug in this crate's wire shapes or a breaking change in the API.
    #[error("undecodable AgentMail response ({reason}): {body}")]
    Decode {
        /// Why deserialization failed.
        reason: String,
        /// The response body, verbatim.
        body: String,
    },
}

/// An authenticated handle on the AgentMail API. Cheap to clone-ish (it owns
/// a pooled `reqwest::Client`); construct once and share by reference.
pub struct Client {
    http: reqwest::Client,
    base_url: String,
    api_key: String,
}

// Manual impl so an accidental `{:?}` never prints the API key.
impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("base_url", &self.base_url)
            .field("api_key", &"[redacted]")
            .finish_non_exhaustive()
    }
}

impl Client {
    /// A client against `base_url` (see [`DEFAULT_BASE_URL`]), with a
    /// [`DEFAULT_TIMEOUT`] on every request.
    pub fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
        // We build reqwest with rustls but no bundled crypto provider, so install
        // `ring` as the process default (no aws-lc-rs / cmake). This is a global,
        // set-once operation: it no-ops if the host application already installed
        // a provider, so it never overrides a deliberate choice.
        let _ = rustls::crypto::ring::default_provider().install_default();
        Client {
            http: reqwest::Client::builder()
                .timeout(DEFAULT_TIMEOUT)
                .build()
                // Infallible for these options; build() can only fail on
                // TLS-backend misconfiguration.
                .expect("reqwest client"),
            base_url: base_url.into().trim_end_matches('/').to_string(),
            api_key: api_key.into(),
        }
    }

    /// From `AGENTMAIL_API_KEY` (+ optional `AGENTMAIL_BASE_URL`).
    pub fn from_env() -> Result<Self, Error> {
        let key = std::env::var("AGENTMAIL_API_KEY").map_err(|_| Error::MissingApiKey)?;
        let base =
            std::env::var("AGENTMAIL_BASE_URL").unwrap_or_else(|_| DEFAULT_BASE_URL.to_string());
        Ok(Self::new(key, base))
    }

    async fn request<T: serde::de::DeserializeOwned>(
        &self,
        method: reqwest::Method,
        path: &str,
        query: &[(&str, String)],
        body: Option<serde_json::Value>,
    ) -> Result<T, Error> {
        let mut req = self
            .http
            .request(method, format!("{}{path}", self.base_url))
            .bearer_auth(&self.api_key);
        if !query.is_empty() {
            req = req.query(query);
        }
        if let Some(body) = body {
            req = req.json(&body);
        }
        let resp = req.send().await?;
        let status = resp.status();
        let text = resp.text().await.unwrap_or_default();
        if !status.is_success() {
            return Err(Error::Api { status, body: text });
        }
        // DELETE endpoints answer with an empty body; map that to null so
        // `()` (unit) deserializes.
        let text = if text.trim().is_empty() {
            "null"
        } else {
            &text
        };
        serde_json::from_str(text).map_err(|e| Error::Decode {
            reason: e.to_string(),
            body: text.to_string(),
        })
    }

    // ── Inboxes ──────────────────────────────────────────────────────────────

    /// POST /v0/inboxes, a new agent-owned email address. Free plans get
    /// `{username}@agentmail.to`; custom domains must be verified first.
    pub async fn create_inbox(&self, inbox: CreateInbox) -> Result<Inbox, Error> {
        self.request(
            reqwest::Method::POST,
            "/v0/inboxes",
            &[],
            Some(serde_json::to_value(inbox).expect("serializable")),
        )
        .await
    }

    /// GET /v0/inboxes (first page; see [`Client::list_inboxes_page`]).
    pub async fn list_inboxes(&self) -> Result<InboxList, Error> {
        self.list_inboxes_page(Page::default()).await
    }

    /// GET /v0/inboxes with pagination. Feed [`InboxList::next_page_token`]
    /// back in as [`Page::page_token`] until it comes back `None`.
    pub async fn list_inboxes_page(&self, page: Page) -> Result<InboxList, Error> {
        self.request(reqwest::Method::GET, "/v0/inboxes", &page.query(), None)
            .await
    }

    /// GET /v0/inboxes/{inbox_id}
    pub async fn get_inbox(&self, inbox_id: &str) -> Result<Inbox, Error> {
        self.request(
            reqwest::Method::GET,
            &format!("/v0/inboxes/{}", urlish(inbox_id)),
            &[],
            None,
        )
        .await
    }

    /// DELETE /v0/inboxes/{inbox_id}
    pub async fn delete_inbox(&self, inbox_id: &str) -> Result<(), Error> {
        self.request(
            reqwest::Method::DELETE,
            &format!("/v0/inboxes/{}", urlish(inbox_id)),
            &[],
            None,
        )
        .await
    }

    // ── Messages ─────────────────────────────────────────────────────────────

    /// POST /v0/inboxes/{inbox_id}/messages/send
    pub async fn send_message(
        &self,
        inbox_id: &str,
        message: SendMessage,
    ) -> Result<SentMessage, Error> {
        self.request(
            reqwest::Method::POST,
            &format!("/v0/inboxes/{}/messages/send", urlish(inbox_id)),
            &[],
            Some(serde_json::to_value(message).expect("serializable")),
        )
        .await
    }

    /// GET /v0/inboxes/{inbox_id}/messages (first page; see
    /// [`Client::list_messages_page`]).
    pub async fn list_messages(&self, inbox_id: &str) -> Result<MessageList, Error> {
        self.list_messages_page(inbox_id, Page::default()).await
    }

    /// GET /v0/inboxes/{inbox_id}/messages with pagination. Feed
    /// [`MessageList::next_page_token`] back in as [`Page::page_token`]
    /// until it comes back `None`.
    pub async fn list_messages_page(
        &self,
        inbox_id: &str,
        page: Page,
    ) -> Result<MessageList, Error> {
        self.request(
            reqwest::Method::GET,
            &format!("/v0/inboxes/{}/messages", urlish(inbox_id)),
            &page.query(),
            None,
        )
        .await
    }

    /// GET /v0/inboxes/{inbox_id}/messages/{message_id}
    pub async fn get_message(&self, inbox_id: &str, message_id: &str) -> Result<Message, Error> {
        self.request(
            reqwest::Method::GET,
            &format!(
                "/v0/inboxes/{}/messages/{}",
                urlish(inbox_id),
                urlish(message_id),
            ),
            &[],
            None,
        )
        .await
    }

    // ── Webhooks ─────────────────────────────────────────────────────────────

    /// POST /v0/webhooks, subscribe an HTTPS endpoint to events
    /// (e.g. `message.received`). The response carries the signing `secret`
    /// exactly once; store it.
    pub async fn create_webhook(&self, webhook: CreateWebhook) -> Result<Webhook, Error> {
        self.request(
            reqwest::Method::POST,
            "/v0/webhooks",
            &[],
            Some(serde_json::to_value(webhook).expect("serializable")),
        )
        .await
    }

    /// GET /v0/webhooks (first page; see [`Client::list_webhooks_page`]).
    pub async fn list_webhooks(&self) -> Result<WebhookList, Error> {
        self.list_webhooks_page(Page::default()).await
    }

    /// GET /v0/webhooks with pagination. Feed [`WebhookList::next_page_token`]
    /// back in as [`Page::page_token`] until it comes back `None`.
    pub async fn list_webhooks_page(&self, page: Page) -> Result<WebhookList, Error> {
        self.request(reqwest::Method::GET, "/v0/webhooks", &page.query(), None)
            .await
    }

    /// DELETE /v0/webhooks/{webhook_id}
    pub async fn delete_webhook(&self, webhook_id: &str) -> Result<(), Error> {
        self.request(
            reqwest::Method::DELETE,
            &format!("/v0/webhooks/{}", urlish(webhook_id)),
            &[],
            None,
        )
        .await
    }
}

/// Minimal percent-encoding for path segments (ids are URL-safe in practice;
/// this keeps a stray space, slash, or non-ASCII char from corrupting the
/// path). Encodes per UTF-8 byte, as percent-encoding requires.
fn urlish(segment: &str) -> String {
    segment
        .bytes()
        .map(|b| match b {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'@' | b'+' => {
                (b as char).to_string()
            }
            other => format!("%{other:02X}"),
        })
        .collect()
}

// ─── Types (wire shapes from the OpenAPI spec) ────────────────────────────────

/// Pagination controls for the `list_*_page` calls. `Default` is the API's
/// own defaults (first page, server-chosen page size).
#[derive(Clone, Debug, Default)]
pub struct Page {
    /// Maximum items per page (the API caps this server-side).
    pub limit: Option<u32>,
    /// Cursor from a previous response's `next_page_token`.
    pub page_token: Option<String>,
}

impl Page {
    fn query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(limit) = self.limit {
            q.push(("limit", limit.to_string()));
        }
        if let Some(token) = &self.page_token {
            q.push(("page_token", token.clone()));
        }
        q
    }
}

/// Request body for [`Client::create_inbox`]. All fields optional; the API
/// generates a username when none is given.
#[derive(Clone, Debug, Default, Serialize)]
pub struct CreateInbox {
    /// Local part of the address; random when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
    /// A verified domain (or subdomain of one); defaults to `agentmail.to`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    /// Human-readable sender name shown in email clients.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// Your own idempotency/reference id for this inbox.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    /// Arbitrary JSON stored alongside the inbox.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

/// An agent-owned inbox, as the API returns it.
#[derive(Clone, Debug, Deserialize)]
pub struct Inbox {
    /// Unique id, used in every message call.
    pub inbox_id: String,
    /// The address itself, e.g. `my-agent@agentmail.to`.
    pub email: String,
    /// Human-readable sender name, when set.
    #[serde(default)]
    pub display_name: Option<String>,
    /// Owning pod, when the account uses pods.
    #[serde(default)]
    pub pod_id: Option<String>,
    /// Your reference id from creation, when set.
    #[serde(default)]
    pub client_id: Option<String>,
    /// RFC 3339 creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
}

/// One page of inboxes from [`Client::list_inboxes_page`].
#[derive(Clone, Debug, Deserialize)]
pub struct InboxList {
    /// Total inboxes in the account (not just this page).
    pub count: u64,
    /// This page of inboxes.
    #[serde(default)]
    pub inboxes: Vec<Inbox>,
    /// Cursor for the next page; `None` on the last page.
    #[serde(default)]
    pub next_page_token: Option<String>,
}

/// Request body for [`Client::send_message`]. At least one recipient in `to`
/// and one of `text`/`html` are required by the API.
#[derive(Clone, Debug, Default, Serialize)]
pub struct SendMessage {
    /// Primary recipients.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub to: Vec<String>,
    /// Carbon-copy recipients.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub cc: Vec<String>,
    /// Blind-carbon-copy recipients.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub bcc: Vec<String>,
    /// Subject line.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    /// Plain-text body.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// HTML body (send both for multipart).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
    /// Labels to attach to the sent message.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
}

/// The API's acknowledgement of a send.
#[derive(Clone, Debug, Deserialize)]
pub struct SentMessage {
    /// Id of the message just sent.
    pub message_id: String,
    /// Thread the message was filed under.
    pub thread_id: String,
}

/// A message as the API returns it. List items are a subset of the full
/// get-message shape; every non-id field defaults so both parse.
#[derive(Clone, Debug, Deserialize)]
pub struct Message {
    /// Unique id within the inbox.
    pub message_id: String,
    /// Inbox the message belongs to.
    #[serde(default)]
    pub inbox_id: Option<String>,
    /// Conversation thread id.
    #[serde(default)]
    pub thread_id: Option<String>,
    /// Sender address.
    #[serde(default)]
    pub from: Option<String>,
    /// Recipient addresses.
    #[serde(default)]
    pub to: Vec<String>,
    /// Subject line.
    #[serde(default)]
    pub subject: Option<String>,
    /// Short plain-text excerpt (list responses).
    #[serde(default)]
    pub preview: Option<String>,
    /// Full plain-text body (get responses).
    #[serde(default)]
    pub text: Option<String>,
    /// Full HTML body (get responses).
    #[serde(default)]
    pub html: Option<String>,
    /// Labels on the message (e.g. `received`, `unread`).
    #[serde(default)]
    pub labels: Vec<String>,
    /// RFC 3339 send/receive timestamp.
    #[serde(default)]
    pub timestamp: Option<String>,
}

/// One page of messages from [`Client::list_messages_page`].
#[derive(Clone, Debug, Deserialize)]
pub struct MessageList {
    /// Total messages in the inbox (not just this page).
    pub count: u64,
    /// This page of messages.
    #[serde(default)]
    pub messages: Vec<Message>,
    /// Cursor for the next page; `None` on the last page.
    #[serde(default)]
    pub next_page_token: Option<String>,
}

/// Request body for [`Client::create_webhook`].
#[derive(Clone, Debug, Default, Serialize)]
pub struct CreateWebhook {
    /// HTTPS endpoint to deliver events to.
    pub url: String,
    /// e.g. `["message.received"]`.
    pub event_types: Vec<String>,
    /// Limit delivery to these inboxes; empty means all.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub inbox_ids: Vec<String>,
    /// Your own idempotency/reference id for this webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
}

/// A webhook subscription, as the API returns it.
#[derive(Clone, Debug, Deserialize)]
pub struct Webhook {
    /// Unique id, used to delete the subscription.
    pub webhook_id: String,
    /// The subscribed HTTPS endpoint.
    pub url: String,
    /// Signing secret, returned once, on creation.
    #[serde(default)]
    pub secret: Option<String>,
    /// Subscribed event types.
    #[serde(default)]
    pub event_types: Vec<String>,
    /// Inboxes the subscription is limited to; empty means all.
    #[serde(default)]
    pub inbox_ids: Vec<String>,
    /// Whether the subscription currently delivers.
    pub enabled: bool,
}

/// One page of webhooks from [`Client::list_webhooks_page`].
#[derive(Clone, Debug, Deserialize)]
pub struct WebhookList {
    /// Total webhooks in the account (not just this page).
    pub count: u64,
    /// This page of webhooks.
    #[serde(default)]
    pub webhooks: Vec<Webhook>,
    /// Cursor for the next page; `None` on the last page.
    #[serde(default)]
    pub next_page_token: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wire_shapes_round_trip() {
        // Response example from the OpenAPI spec.
        let inbox: Inbox = serde_json::from_str(
            r#"{"pod_id":"pod_1","inbox_id":"ib_1","email":"x@agentmail.to",
                "display_name":"X","updated_at":"2024-01-15T09:30:00Z",
                "created_at":"2024-01-15T09:30:00Z","surprise_field":1}"#,
        )
        .unwrap();
        assert_eq!(inbox.email, "x@agentmail.to");

        // List items are a subset of the get shape, both must parse.
        let list: MessageList = serde_json::from_str(
            r#"{"count":1,"messages":[{"message_id":"m1","thread_id":"t1",
                "from":"a@b.c","subject":"hi","preview":"…","timestamp":"2026-01-01T00:00:00Z"}]}"#,
        )
        .unwrap();
        assert_eq!(list.messages[0].message_id, "m1");
        assert!(list.messages[0].text.is_none());

        // Requests omit empties so the API's validators stay quiet.
        let body = serde_json::to_value(SendMessage {
            to: vec!["a@b.c".into()],
            subject: Some("s".into()),
            text: Some("t".into()),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(
            body,
            serde_json::json!({"to":["a@b.c"],"subject":"s","text":"t"}),
        );
    }

    #[test]
    fn path_segments_stay_paths() {
        assert_eq!(urlish("ib_abc-123.x@y+z"), "ib_abc-123.x@y+z");
        assert_eq!(urlish("a/b c"), "a%2Fb%20c");
        // Non-ASCII encodes per UTF-8 byte, not per code point.
        assert_eq!(urlish("café"), "caf%C3%A9");
        assert_eq!(urlish("😀"), "%F0%9F%98%80");
    }

    #[test]
    fn page_query_pairs() {
        assert!(Page::default().query().is_empty());
        let q = Page {
            limit: Some(10),
            page_token: Some("tok".into()),
        }
        .query();
        assert_eq!(
            q,
            vec![
                ("limit", "10".to_string()),
                ("page_token", "tok".to_string())
            ],
        );
    }
}