1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct Email {
71 pub from: String,
73 pub to: String,
75 pub subject: String,
77 pub text_body: String,
79 pub html_body: Option<String>,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
85pub struct SentEmail {
86 pub id: String,
88 pub from_addr: String,
90 pub to_addr: String,
92 pub subject: String,
94 pub text_body: String,
96 pub html_body: Option<String>,
98 pub sent_at: String,
100}
101
102#[derive(Clone)]
104pub enum MailTransport {
105 OutboxOnly,
107 Resend {
109 api_key: String,
111 endpoint: String,
113 },
114 Smtp {
116 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 #[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#[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 #[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 #[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 pub fn default_from(&self) -> &str {
198 &self.default_from
199 }
200
201 pub fn transport(&self) -> &MailTransport {
203 &self.transport
204 }
205
206 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 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}