Skip to main content

slabs_mail/
lib.rs

1//! Transactional email delivery and SQLite outbox logging for Slabs applications.
2//!
3//! # Owned table and environment variables
4//!
5//! This crate logs every sent message to the `slabs_mail_outbox` table created by
6//! `Db::init_system_tables`.
7//! Each row stores `id` (`eml_<ulid>`), `from_addr`, `to_addr`, `subject`, `text_body`,
8//! `html_body`, and `sent_at`.
9//!
10//! [`MailTransport::from_env`] selects a delivery backend in this order:
11//!
12//! - `SLABS_RESEND_API_KEY`: selects [`MailTransport::Resend`]. Set `SLABS_RESEND_URL` to
13//!   override the default `https://api.resend.com/emails` endpoint.
14//! - `SLABS_SMTP_URL`: selects [`MailTransport::Smtp`] via `lettre` (for example
15//!   `smtps://user:pass@smtp.host`).
16//! - Neither variable set: selects [`MailTransport::OutboxOnly`].
17//!
18//! # Agent invariants
19//!
20//! - [`Mailer::send`] performs network I/O for Resend and SMTP transports before writing to
21//!   `slabs_mail_outbox`. It does not participate in a SQLite transaction.
22//! - To send email atomically with a domain write, enqueue a job via
23//!   `ctx.jobs.enqueue_in_tx(&mut tx, ...)` and call [`Mailer::send`] inside the job handler.
24//! - In development and tests, [`MailTransport::OutboxOnly`] makes no network calls and stores
25//!   every message in `slabs_mail_outbox`. Inspect sent mail via [`Mailer::list_sent`],
26//!   `TestApp::sent_emails` in tests, or `GET /_slabs/mail` in development.
27//! - Leave [`Email::from`] empty to fall back to [`Mailer::default_from`].
28//!
29//! # Example
30//!
31//! ```rust,no_run
32//! use slabs_db::Db;
33//! use slabs_mail::{Email, MailTransport, Mailer};
34//!
35//! # async fn run() -> slabs_core::SlabResult<()> {
36//! let db = Db::connect("sqlite::memory:").await?;
37//! db.init_system_tables().await?;
38//!
39//! let mailer = Mailer::with_transport(db, "noreply@example.com", MailTransport::from_env());
40//! mailer
41//!     .send(Email {
42//!         from: String::new(),
43//!         to: "user@example.com".into(),
44//!         subject: "Sign in to Slabs".into(),
45//!         text_body: "Use this link to sign in.".into(),
46//!         html_body: Some("<p>Use this link to sign in.</p>".into()),
47//!     })
48//!     .await?;
49//!
50//! let sent = mailer.list_sent(10).await?;
51//! assert_eq!(sent.len(), 1);
52//! # Ok(())
53//! # }
54//! ```
55
56use chrono::Utc;
57use lettre::{
58    message::{header::ContentType, MultiPart},
59    AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
60};
61use serde::{Deserialize, Serialize};
62use serde_json::json;
63use slabs_core::{id, SlabError, SlabResult};
64use slabs_db::Db;
65use std::fmt;
66use std::time::Duration;
67
68/// Outgoing email message passed to [`Mailer::send`].
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct Email {
71    /// Sender address. Uses [`Mailer::default_from`] when empty.
72    pub from: String,
73    /// Recipient email address.
74    pub to: String,
75    /// Message subject line.
76    pub subject: String,
77    /// Plain-text message body.
78    pub text_body: String,
79    /// Optional HTML alternative body.
80    pub html_body: Option<String>,
81}
82
83/// Persisted record of a sent email in the `slabs_mail_outbox` table.
84#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
85pub struct SentEmail {
86    /// Unique email identifier (`eml_<ulid>`).
87    pub id: String,
88    /// Resolved sender email address.
89    pub from_addr: String,
90    /// Recipient email address.
91    pub to_addr: String,
92    /// Message subject line.
93    pub subject: String,
94    /// Plain-text message body.
95    pub text_body: String,
96    /// Optional HTML alternative body.
97    pub html_body: Option<String>,
98    /// RFC 3339 timestamp when [`Mailer::send`] recorded the message.
99    pub sent_at: String,
100}
101
102/// Delivery backend used by [`Mailer`].
103#[derive(Clone)]
104pub enum MailTransport {
105    /// Development and test default. Persists rows to `slabs_mail_outbox` without network I/O.
106    OutboxOnly,
107    /// HTTP delivery through the Resend API (`SLABS_RESEND_API_KEY`).
108    Resend {
109        /// Bearer API key for the Resend API.
110        api_key: String,
111        /// Resend email submission endpoint URL.
112        endpoint: String,
113    },
114    /// SMTP delivery through `lettre` (`SLABS_SMTP_URL`, for example `smtps://user:pass@smtp.host`).
115    Smtp {
116        /// SMTP connection URL parsed by `lettre`.
117        url: String,
118    },
119}
120
121impl fmt::Debug for MailTransport {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        match self {
124            Self::OutboxOnly => f.write_str("OutboxOnly"),
125            Self::Resend { endpoint, .. } => f
126                .debug_struct("Resend")
127                .field("api_key", &"<redacted>")
128                .field("endpoint", endpoint)
129                .finish(),
130            Self::Smtp { .. } => f.debug_struct("Smtp").field("url", &"<redacted>").finish(),
131        }
132    }
133}
134
135impl MailTransport {
136    /// Detect the mail transport from `SLABS_RESEND_API_KEY` or `SLABS_SMTP_URL`.
137    ///
138    /// Checks `SLABS_RESEND_API_KEY` first, then `SLABS_SMTP_URL`, and defaults to
139    /// [`MailTransport::OutboxOnly`].
140    #[must_use]
141    pub fn from_env() -> Self {
142        if let Ok(api_key) = std::env::var("SLABS_RESEND_API_KEY") {
143            if !api_key.trim().is_empty() {
144                let endpoint = std::env::var("SLABS_RESEND_URL")
145                    .unwrap_or_else(|_| "https://api.resend.com/emails".to_string());
146                return Self::Resend { api_key, endpoint };
147            }
148        }
149        if let Ok(url) = std::env::var("SLABS_SMTP_URL") {
150            if !url.trim().is_empty() {
151                return Self::Smtp { url };
152            }
153        }
154        Self::OutboxOnly
155    }
156}
157
158/// Outbound email client backed by [`MailTransport`] and `slabs_mail_outbox`.
159///
160/// Delivers each message through the configured transport and records a copy in
161/// `slabs_mail_outbox`.
162#[derive(Debug, Clone)]
163pub struct Mailer {
164    db: Db,
165    default_from: String,
166    transport: MailTransport,
167    http: reqwest::Client,
168}
169
170impl Mailer {
171    /// Create a mailer using [`MailTransport::OutboxOnly`].
172    #[must_use]
173    pub fn new(db: Db, default_from: impl Into<String>) -> Self {
174        Self::with_transport(db, default_from, MailTransport::OutboxOnly)
175    }
176
177    /// Create a mailer with an explicit [`MailTransport`] backend and a 10-second HTTP timeout.
178    #[must_use]
179    pub fn with_transport(
180        db: Db,
181        default_from: impl Into<String>,
182        transport: MailTransport,
183    ) -> Self {
184        let http = reqwest::Client::builder()
185            .timeout(Duration::from_secs(10))
186            .build()
187            .expect("failed to build reqwest client");
188        Self {
189            db,
190            default_from: default_from.into(),
191            transport,
192            http,
193        }
194    }
195
196    /// Return the default sender address used when [`Email::from`] is empty.
197    pub fn default_from(&self) -> &str {
198        &self.default_from
199    }
200
201    /// Return the configured [`MailTransport`] backend.
202    pub fn transport(&self) -> &MailTransport {
203        &self.transport
204    }
205
206    /// Deliver `email` via the active transport and insert a row into `slabs_mail_outbox`.
207    ///
208    /// Returns an error without inserting into `slabs_mail_outbox` if Resend or SMTP delivery fails.
209    pub async fn send(&self, email: Email) -> SlabResult<SentEmail> {
210        let mail_id = id::new("eml");
211        let sent_at = Utc::now().to_rfc3339();
212        let from_addr = if email.from.is_empty() {
213            self.default_from.clone()
214        } else {
215            email.from
216        };
217
218        let record = SentEmail {
219            id: mail_id,
220            from_addr,
221            to_addr: email.to,
222            subject: email.subject,
223            text_body: email.text_body,
224            html_body: email.html_body,
225            sent_at,
226        };
227
228        match &self.transport {
229            MailTransport::OutboxOnly => {}
230            MailTransport::Resend { api_key, endpoint } => {
231                let mut payload = json!({
232                    "from": record.from_addr,
233                    "to": [record.to_addr],
234                    "subject": record.subject,
235                    "text": record.text_body,
236                });
237                if let Some(html) = &record.html_body {
238                    payload["html"] = json!(html);
239                }
240
241                let resp = self
242                    .http
243                    .post(endpoint)
244                    .bearer_auth(api_key)
245                    .json(&payload)
246                    .send()
247                    .await
248                    .map_err(|e| SlabError::internal(format!("resend request failed: {e}")))?;
249
250                if !resp.status().is_success() {
251                    let status = resp.status();
252                    let body = resp.text().await.unwrap_or_default();
253                    return Err(SlabError::internal(format!(
254                        "resend API error {status}: {body}"
255                    )));
256                }
257            }
258            MailTransport::Smtp { url } => {
259                let mailer = AsyncSmtpTransport::<Tokio1Executor>::from_url(url)
260                    .map_err(|e| SlabError::internal(format!("invalid SLABS_SMTP_URL: {e}")))?
261                    .build();
262
263                let builder =
264                    Message::builder()
265                        .from(record.from_addr.parse().map_err(|e| {
266                            SlabError::bad_request(format!("invalid from addr: {e}"))
267                        })?)
268                        .to(record
269                            .to_addr
270                            .parse()
271                            .map_err(|e| SlabError::bad_request(format!("invalid to addr: {e}")))?)
272                        .subject(&record.subject);
273
274                let msg = if let Some(html) = &record.html_body {
275                    builder
276                        .multipart(MultiPart::alternative_plain_html(
277                            record.text_body.clone(),
278                            html.clone(),
279                        ))
280                        .map_err(|e| SlabError::internal(format!("smtp build failed: {e}")))?
281                } else {
282                    builder
283                        .header(ContentType::TEXT_PLAIN)
284                        .body(record.text_body.clone())
285                        .map_err(|e| SlabError::internal(format!("smtp build failed: {e}")))?
286                };
287
288                mailer
289                    .send(msg)
290                    .await
291                    .map_err(|e| SlabError::internal(format!("smtp send failed: {e}")))?;
292            }
293        }
294
295        sqlx::query(
296            "INSERT INTO slabs_mail_outbox (id, from_addr, to_addr, subject, text_body, html_body, sent_at)
297             VALUES (?, ?, ?, ?, ?, ?, ?)",
298        )
299        .bind(&record.id)
300        .bind(&record.from_addr)
301        .bind(&record.to_addr)
302        .bind(&record.subject)
303        .bind(&record.text_body)
304        .bind(&record.html_body)
305        .bind(&record.sent_at)
306        .execute(self.db.pool())
307        .await?;
308
309        tracing::info!(mail_id = %record.id, to = %record.to_addr, subject = %record.subject, "email delivered");
310
311        Ok(record)
312    }
313
314    /// Return up to `limit` rows from `slabs_mail_outbox` ordered from newest to oldest `sent_at`.
315    pub async fn list_sent(&self, limit: i64) -> SlabResult<Vec<SentEmail>> {
316        let rows: Vec<SentEmail> = sqlx::query_as(
317            "SELECT id, from_addr, to_addr, subject, text_body, html_body, sent_at
318             FROM slabs_mail_outbox
319             ORDER BY sent_at DESC
320             LIMIT ?",
321        )
322        .bind(limit)
323        .fetch_all(self.db.pool())
324        .await?;
325        Ok(rows)
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332    use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
333    use std::sync::{Arc, Mutex};
334
335    type CapturedRequest = Arc<Mutex<Option<(String, serde_json::Value)>>>;
336
337    #[tokio::test]
338    async fn resend_transport_sends_bearer_auth_and_json_body() {
339        let captured: CapturedRequest = Arc::new(Mutex::new(None));
340        let cap_clone = captured.clone();
341
342        let app = Router::new()
343            .route(
344                "/emails",
345                post(
346                    |State(cap): State<CapturedRequest>,
347                     headers: HeaderMap,
348                     Json(body): Json<serde_json::Value>| async move {
349                        let auth = headers
350                            .get("authorization")
351                            .and_then(|v| v.to_str().ok())
352                            .unwrap_or("")
353                            .to_string();
354                        *cap.lock().unwrap() = Some((auth, body));
355                        Json(json!({ "id": "re_123" }))
356                    },
357                ),
358            )
359            .with_state(cap_clone);
360
361        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
362        let addr = listener.local_addr().unwrap();
363        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
364
365        let db = Db::connect("sqlite::memory:").await.unwrap();
366        db.init_system_tables().await.unwrap();
367
368        let mailer = Mailer::with_transport(
369            db,
370            "noreply@slabs.dev",
371            MailTransport::Resend {
372                api_key: "re_test_key".into(),
373                endpoint: format!("http://{addr}/emails"),
374            },
375        );
376
377        mailer
378            .send(Email {
379                from: String::new(),
380                to: "dhh@37signals.com".into(),
381                subject: "Hello Resend".into(),
382                text_body: "Works!".into(),
383                html_body: Some("<p>Works!</p>".into()),
384            })
385            .await
386            .unwrap();
387
388        let (auth, body) = captured.lock().unwrap().clone().expect("request captured");
389        assert_eq!(auth, "Bearer re_test_key");
390        assert_eq!(body["to"][0], "dhh@37signals.com");
391        assert_eq!(body["subject"], "Hello Resend");
392        assert_eq!(body["html"], "<p>Works!</p>");
393    }
394
395    #[test]
396    fn mail_transport_debug_redacts_credentials() {
397        let resend = MailTransport::Resend {
398            api_key: "re_live_secret".into(),
399            endpoint: "https://api.resend.com/emails".into(),
400        };
401        let resend_dbg = format!("{resend:?}");
402        assert!(!resend_dbg.contains("re_live_secret"));
403        assert!(resend_dbg.contains("<redacted>"));
404        assert!(resend_dbg.contains("https://api.resend.com/emails"));
405
406        let smtp = MailTransport::Smtp {
407            url: "smtps://user:hunter2@smtp.example.com".into(),
408        };
409        let smtp_dbg = format!("{smtp:?}");
410        assert!(!smtp_dbg.contains("hunter2"));
411        assert!(smtp_dbg.contains("<redacted>"));
412    }
413}