slabs-mail 0.2.0

Low-level transactional mailer battery with SQLite dev/test outbox, Resend HTTP, and SMTP (lettre) transports
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
//! Transactional email delivery and SQLite outbox logging for Slabs applications.
//!
//! # Owned table and environment variables
//!
//! This crate logs every sent message to the `slabs_mail_outbox` table created by
//! `Db::init_system_tables`.
//! Each row stores `id` (`eml_<ulid>`), `from_addr`, `to_addr`, `subject`, `text_body`,
//! `html_body`, and `sent_at`.
//!
//! [`MailTransport::from_env`] selects a delivery backend in this order:
//!
//! - `SLABS_RESEND_API_KEY`: selects [`MailTransport::Resend`]. Set `SLABS_RESEND_URL` to
//!   override the default `https://api.resend.com/emails` endpoint.
//! - `SLABS_SMTP_URL`: selects [`MailTransport::Smtp`] via `lettre` (for example
//!   `smtps://user:pass@smtp.host`).
//! - Neither variable set: selects [`MailTransport::OutboxOnly`].
//!
//! # Agent invariants
//!
//! - [`Mailer::send`] performs network I/O for Resend and SMTP transports before writing to
//!   `slabs_mail_outbox`. It does not participate in a SQLite transaction.
//! - To send email atomically with a domain write, enqueue a job via
//!   `ctx.jobs.enqueue_in_tx(&mut tx, ...)` and call [`Mailer::send`] inside the job handler.
//! - In development and tests, [`MailTransport::OutboxOnly`] makes no network calls and stores
//!   every message in `slabs_mail_outbox`. Inspect sent mail via [`Mailer::list_sent`],
//!   `TestApp::sent_emails` in tests, or `GET /_slabs/mail` in development.
//! - Leave [`Email::from`] empty to fall back to [`Mailer::default_from`].
//!
//! # Example
//!
//! ```rust,no_run
//! use slabs_db::Db;
//! use slabs_mail::{Email, MailTransport, Mailer};
//!
//! # async fn run() -> slabs_core::SlabResult<()> {
//! let db = Db::connect("sqlite::memory:").await?;
//! db.init_system_tables().await?;
//!
//! let mailer = Mailer::with_transport(db, "noreply@example.com", MailTransport::from_env());
//! mailer
//!     .send(Email {
//!         from: String::new(),
//!         to: "user@example.com".into(),
//!         subject: "Sign in to Slabs".into(),
//!         text_body: "Use this link to sign in.".into(),
//!         html_body: Some("<p>Use this link to sign in.</p>".into()),
//!     })
//!     .await?;
//!
//! let sent = mailer.list_sent(10).await?;
//! assert_eq!(sent.len(), 1);
//! # Ok(())
//! # }
//! ```

use chrono::Utc;
use lettre::{
    message::{header::ContentType, MultiPart},
    AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use slabs_core::{id, SlabError, SlabResult};
use slabs_db::Db;
use std::fmt;
use std::time::Duration;

/// Outgoing email message passed to [`Mailer::send`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Email {
    /// Sender address. Uses [`Mailer::default_from`] when empty.
    pub from: String,
    /// Recipient email address.
    pub to: String,
    /// Message subject line.
    pub subject: String,
    /// Plain-text message body.
    pub text_body: String,
    /// Optional HTML alternative body.
    pub html_body: Option<String>,
}

/// Persisted record of a sent email in the `slabs_mail_outbox` table.
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct SentEmail {
    /// Unique email identifier (`eml_<ulid>`).
    pub id: String,
    /// Resolved sender email address.
    pub from_addr: String,
    /// Recipient email address.
    pub to_addr: String,
    /// Message subject line.
    pub subject: String,
    /// Plain-text message body.
    pub text_body: String,
    /// Optional HTML alternative body.
    pub html_body: Option<String>,
    /// RFC 3339 timestamp when [`Mailer::send`] recorded the message.
    pub sent_at: String,
}

/// Delivery backend used by [`Mailer`].
#[derive(Clone)]
pub enum MailTransport {
    /// Development and test default. Persists rows to `slabs_mail_outbox` without network I/O.
    OutboxOnly,
    /// HTTP delivery through the Resend API (`SLABS_RESEND_API_KEY`).
    Resend {
        /// Bearer API key for the Resend API.
        api_key: String,
        /// Resend email submission endpoint URL.
        endpoint: String,
    },
    /// SMTP delivery through `lettre` (`SLABS_SMTP_URL`, for example `smtps://user:pass@smtp.host`).
    Smtp {
        /// SMTP connection URL parsed by `lettre`.
        url: String,
    },
}

impl fmt::Debug for MailTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OutboxOnly => f.write_str("OutboxOnly"),
            Self::Resend { endpoint, .. } => f
                .debug_struct("Resend")
                .field("api_key", &"<redacted>")
                .field("endpoint", endpoint)
                .finish(),
            Self::Smtp { .. } => f.debug_struct("Smtp").field("url", &"<redacted>").finish(),
        }
    }
}

impl MailTransport {
    /// Detect the mail transport from `SLABS_RESEND_API_KEY` or `SLABS_SMTP_URL`.
    ///
    /// Checks `SLABS_RESEND_API_KEY` first, then `SLABS_SMTP_URL`, and defaults to
    /// [`MailTransport::OutboxOnly`].
    #[must_use]
    pub fn from_env() -> Self {
        if let Ok(api_key) = std::env::var("SLABS_RESEND_API_KEY") {
            if !api_key.trim().is_empty() {
                let endpoint = std::env::var("SLABS_RESEND_URL")
                    .unwrap_or_else(|_| "https://api.resend.com/emails".to_string());
                return Self::Resend { api_key, endpoint };
            }
        }
        if let Ok(url) = std::env::var("SLABS_SMTP_URL") {
            if !url.trim().is_empty() {
                return Self::Smtp { url };
            }
        }
        Self::OutboxOnly
    }
}

/// Outbound email client backed by [`MailTransport`] and `slabs_mail_outbox`.
///
/// Delivers each message through the configured transport and records a copy in
/// `slabs_mail_outbox`.
#[derive(Debug, Clone)]
pub struct Mailer {
    db: Db,
    default_from: String,
    transport: MailTransport,
    http: reqwest::Client,
}

impl Mailer {
    /// Create a mailer using [`MailTransport::OutboxOnly`].
    #[must_use]
    pub fn new(db: Db, default_from: impl Into<String>) -> Self {
        Self::with_transport(db, default_from, MailTransport::OutboxOnly)
    }

    /// Create a mailer with an explicit [`MailTransport`] backend and a 10-second HTTP timeout.
    #[must_use]
    pub fn with_transport(
        db: Db,
        default_from: impl Into<String>,
        transport: MailTransport,
    ) -> Self {
        let http = reqwest::Client::builder()
            .timeout(Duration::from_secs(10))
            .build()
            .expect("failed to build reqwest client");
        Self {
            db,
            default_from: default_from.into(),
            transport,
            http,
        }
    }

    /// Return the default sender address used when [`Email::from`] is empty.
    pub fn default_from(&self) -> &str {
        &self.default_from
    }

    /// Return the configured [`MailTransport`] backend.
    pub fn transport(&self) -> &MailTransport {
        &self.transport
    }

    /// Deliver `email` via the active transport and insert a row into `slabs_mail_outbox`.
    ///
    /// Returns an error without inserting into `slabs_mail_outbox` if Resend or SMTP delivery fails.
    pub async fn send(&self, email: Email) -> SlabResult<SentEmail> {
        let mail_id = id::new("eml");
        let sent_at = Utc::now().to_rfc3339();
        let from_addr = if email.from.is_empty() {
            self.default_from.clone()
        } else {
            email.from
        };

        let record = SentEmail {
            id: mail_id,
            from_addr,
            to_addr: email.to,
            subject: email.subject,
            text_body: email.text_body,
            html_body: email.html_body,
            sent_at,
        };

        match &self.transport {
            MailTransport::OutboxOnly => {}
            MailTransport::Resend { api_key, endpoint } => {
                let mut payload = json!({
                    "from": record.from_addr,
                    "to": [record.to_addr],
                    "subject": record.subject,
                    "text": record.text_body,
                });
                if let Some(html) = &record.html_body {
                    payload["html"] = json!(html);
                }

                let resp = self
                    .http
                    .post(endpoint)
                    .bearer_auth(api_key)
                    .json(&payload)
                    .send()
                    .await
                    .map_err(|e| SlabError::internal(format!("resend request failed: {e}")))?;

                if !resp.status().is_success() {
                    let status = resp.status();
                    let body = resp.text().await.unwrap_or_default();
                    return Err(SlabError::internal(format!(
                        "resend API error {status}: {body}"
                    )));
                }
            }
            MailTransport::Smtp { url } => {
                let mailer = AsyncSmtpTransport::<Tokio1Executor>::from_url(url)
                    .map_err(|e| SlabError::internal(format!("invalid SLABS_SMTP_URL: {e}")))?
                    .build();

                let builder =
                    Message::builder()
                        .from(record.from_addr.parse().map_err(|e| {
                            SlabError::bad_request(format!("invalid from addr: {e}"))
                        })?)
                        .to(record
                            .to_addr
                            .parse()
                            .map_err(|e| SlabError::bad_request(format!("invalid to addr: {e}")))?)
                        .subject(&record.subject);

                let msg = if let Some(html) = &record.html_body {
                    builder
                        .multipart(MultiPart::alternative_plain_html(
                            record.text_body.clone(),
                            html.clone(),
                        ))
                        .map_err(|e| SlabError::internal(format!("smtp build failed: {e}")))?
                } else {
                    builder
                        .header(ContentType::TEXT_PLAIN)
                        .body(record.text_body.clone())
                        .map_err(|e| SlabError::internal(format!("smtp build failed: {e}")))?
                };

                mailer
                    .send(msg)
                    .await
                    .map_err(|e| SlabError::internal(format!("smtp send failed: {e}")))?;
            }
        }

        sqlx::query(
            "INSERT INTO slabs_mail_outbox (id, from_addr, to_addr, subject, text_body, html_body, sent_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&record.id)
        .bind(&record.from_addr)
        .bind(&record.to_addr)
        .bind(&record.subject)
        .bind(&record.text_body)
        .bind(&record.html_body)
        .bind(&record.sent_at)
        .execute(self.db.pool())
        .await?;

        tracing::info!(mail_id = %record.id, to = %record.to_addr, subject = %record.subject, "email delivered");

        Ok(record)
    }

    /// Return up to `limit` rows from `slabs_mail_outbox` ordered from newest to oldest `sent_at`.
    pub async fn list_sent(&self, limit: i64) -> SlabResult<Vec<SentEmail>> {
        let rows: Vec<SentEmail> = sqlx::query_as(
            "SELECT id, from_addr, to_addr, subject, text_body, html_body, sent_at
             FROM slabs_mail_outbox
             ORDER BY sent_at DESC
             LIMIT ?",
        )
        .bind(limit)
        .fetch_all(self.db.pool())
        .await?;
        Ok(rows)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
    use std::sync::{Arc, Mutex};

    type CapturedRequest = Arc<Mutex<Option<(String, serde_json::Value)>>>;

    #[tokio::test]
    async fn resend_transport_sends_bearer_auth_and_json_body() {
        let captured: CapturedRequest = Arc::new(Mutex::new(None));
        let cap_clone = captured.clone();

        let app = Router::new()
            .route(
                "/emails",
                post(
                    |State(cap): State<CapturedRequest>,
                     headers: HeaderMap,
                     Json(body): Json<serde_json::Value>| async move {
                        let auth = headers
                            .get("authorization")
                            .and_then(|v| v.to_str().ok())
                            .unwrap_or("")
                            .to_string();
                        *cap.lock().unwrap() = Some((auth, body));
                        Json(json!({ "id": "re_123" }))
                    },
                ),
            )
            .with_state(cap_clone);

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();

        let mailer = Mailer::with_transport(
            db,
            "noreply@slabs.dev",
            MailTransport::Resend {
                api_key: "re_test_key".into(),
                endpoint: format!("http://{addr}/emails"),
            },
        );

        mailer
            .send(Email {
                from: String::new(),
                to: "dhh@37signals.com".into(),
                subject: "Hello Resend".into(),
                text_body: "Works!".into(),
                html_body: Some("<p>Works!</p>".into()),
            })
            .await
            .unwrap();

        let (auth, body) = captured.lock().unwrap().clone().expect("request captured");
        assert_eq!(auth, "Bearer re_test_key");
        assert_eq!(body["to"][0], "dhh@37signals.com");
        assert_eq!(body["subject"], "Hello Resend");
        assert_eq!(body["html"], "<p>Works!</p>");
    }

    #[test]
    fn mail_transport_debug_redacts_credentials() {
        let resend = MailTransport::Resend {
            api_key: "re_live_secret".into(),
            endpoint: "https://api.resend.com/emails".into(),
        };
        let resend_dbg = format!("{resend:?}");
        assert!(!resend_dbg.contains("re_live_secret"));
        assert!(resend_dbg.contains("<redacted>"));
        assert!(resend_dbg.contains("https://api.resend.com/emails"));

        let smtp = MailTransport::Smtp {
            url: "smtps://user:hunter2@smtp.example.com".into(),
        };
        let smtp_dbg = format!("{smtp:?}");
        assert!(!smtp_dbg.contains("hunter2"));
        assert!(smtp_dbg.contains("<redacted>"));
    }
}