rustango 0.30.25

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! Email backend layer — pluggable async email sending.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::email::{Mailer, Email, ConsoleMailer};
//! use std::sync::Arc;
//!
//! let mailer: Arc<dyn Mailer> = Arc::new(ConsoleMailer::default());
//!
//! let email = Email::new()
//!     .to("user@example.com")
//!     .from("noreply@my-app.com")
//!     .subject("Welcome!")
//!     .body("Thanks for signing up.");
//! mailer.send(&email).await?;
//! ```
//!
//! ## Backends
//!
//! | Backend | When to use |
//! |---------|-------------|
//! | [`ConsoleMailer`] | Development — prints emails to stdout. Default. |
//! | [`InMemoryMailer`] | Tests — captures emails into a `Vec` for assertions. |
//! | [`SmtpMailer`] | Production — connects to an SMTP relay. (Future slice — currently a stub.) |
//!
//! ## Plug your own
//!
//! Implement `Mailer` for any third-party transport (SES, SendGrid, Postmark):
//!
//! ```ignore
//! use rustango::email::{Mailer, Email, MailError};
//! use async_trait::async_trait;
//!
//! pub struct SesMailer { /* ... */ }
//!
//! #[async_trait]
//! impl Mailer for SesMailer {
//!     async fn send(&self, email: &Email) -> Result<(), MailError> {
//!         // POST to AWS SES, etc.
//!         Ok(())
//!     }
//! }
//! ```

use std::sync::{Arc, Mutex};

use async_trait::async_trait;

// ------------------------------------------------------------------ Email

/// One outbound email. Use the builder methods to assemble.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct Email {
    pub to: Vec<String>,
    pub cc: Vec<String>,
    pub bcc: Vec<String>,
    pub from: Option<String>,
    pub reply_to: Option<String>,
    pub subject: String,
    pub body: String,
    pub html_body: Option<String>,
    pub headers: Vec<(String, String)>,
}

impl Email {
    /// Construct an empty email — chain builder methods to fill in fields.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a `To` recipient. Call multiple times for multiple recipients.
    #[must_use]
    pub fn to(mut self, addr: impl Into<String>) -> Self {
        self.to.push(addr.into());
        self
    }

    /// Add a `Cc` recipient.
    #[must_use]
    pub fn cc(mut self, addr: impl Into<String>) -> Self {
        self.cc.push(addr.into());
        self
    }

    /// Add a `Bcc` recipient.
    #[must_use]
    pub fn bcc(mut self, addr: impl Into<String>) -> Self {
        self.bcc.push(addr.into());
        self
    }

    /// Set the `From` address.
    #[must_use]
    pub fn from(mut self, addr: impl Into<String>) -> Self {
        self.from = Some(addr.into());
        self
    }

    /// Set the `Reply-To` address.
    #[must_use]
    pub fn reply_to(mut self, addr: impl Into<String>) -> Self {
        self.reply_to = Some(addr.into());
        self
    }

    /// Set the subject line.
    #[must_use]
    pub fn subject(mut self, s: impl Into<String>) -> Self {
        self.subject = s.into();
        self
    }

    /// Set the plaintext body.
    #[must_use]
    pub fn body(mut self, b: impl Into<String>) -> Self {
        self.body = b.into();
        self
    }

    /// Set an HTML alternative body. Sent as a multipart/alternative MIME
    /// when both `body` and `html_body` are present.
    #[must_use]
    pub fn html_body(mut self, b: impl Into<String>) -> Self {
        self.html_body = Some(b.into());
        self
    }

    /// Add a custom header.
    #[must_use]
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((key.into(), value.into()));
        self
    }

    /// Validate the minimum required fields: at least one recipient + non-empty subject.
    pub fn validate(&self) -> Result<(), MailError> {
        if self.to.is_empty() && self.cc.is_empty() && self.bcc.is_empty() {
            return Err(MailError::InvalidMessage("no recipients".into()));
        }
        if self.subject.is_empty() {
            return Err(MailError::InvalidMessage("subject is empty".into()));
        }
        Ok(())
    }
}

// ------------------------------------------------------------------ MailError

#[derive(Debug, thiserror::Error)]
pub enum MailError {
    #[error("invalid message: {0}")]
    InvalidMessage(String),
    #[error("transport error: {0}")]
    Transport(String),
}

// ------------------------------------------------------------------ Mailer trait

/// Pluggable async email backend.
#[async_trait]
pub trait Mailer: Send + Sync + 'static {
    /// Send `email`. Implementations should validate before transmitting
    /// (the helper [`Email::validate`] is the canonical check).
    async fn send(&self, email: &Email) -> Result<(), MailError>;
}

/// `Arc<dyn Mailer>` alias.
pub type BoxedMailer = Arc<dyn Mailer>;

// ------------------------------------------------------------------ ConsoleMailer

/// Development mailer — prints emails to stdout instead of sending.
#[derive(Default)]
pub struct ConsoleMailer;

#[async_trait]
impl Mailer for ConsoleMailer {
    async fn send(&self, email: &Email) -> Result<(), MailError> {
        email.validate()?;
        println!("============= [ConsoleMailer] outgoing =============");
        if let Some(f) = &email.from {
            println!("From: {f}");
        }
        if !email.to.is_empty() {
            println!("To: {}", email.to.join(", "));
        }
        if !email.cc.is_empty() {
            println!("Cc: {}", email.cc.join(", "));
        }
        if !email.bcc.is_empty() {
            println!("Bcc: {}", email.bcc.join(", "));
        }
        if let Some(rt) = &email.reply_to {
            println!("Reply-To: {rt}");
        }
        println!("Subject: {}", email.subject);
        for (k, v) in &email.headers {
            println!("{k}: {v}");
        }
        println!();
        println!("{}", email.body);
        if let Some(html) = &email.html_body {
            println!("\n--- HTML alternative ---\n{html}");
        }
        println!("====================================================");
        Ok(())
    }
}

// ------------------------------------------------------------------ InMemoryMailer

/// Test mailer — captures every sent email into a shared `Vec` for assertions.
#[derive(Default)]
pub struct InMemoryMailer {
    sent: Mutex<Vec<Email>>,
}

impl InMemoryMailer {
    #[must_use]
    pub fn new() -> Self {
        Self {
            sent: Mutex::new(Vec::new()),
        }
    }

    /// Snapshot all emails sent so far. Doesn't clear the buffer.
    #[must_use]
    pub fn sent(&self) -> Vec<Email> {
        self.sent.lock().expect("sent mutex poisoned").clone()
    }

    /// Number of emails sent so far.
    #[must_use]
    pub fn count(&self) -> usize {
        self.sent.lock().expect("sent mutex poisoned").len()
    }

    /// Clear the captured email buffer.
    pub fn clear(&self) {
        self.sent.lock().expect("sent mutex poisoned").clear();
    }
}

#[async_trait]
impl Mailer for InMemoryMailer {
    async fn send(&self, email: &Email) -> Result<(), MailError> {
        email.validate()?;
        self.sent
            .lock()
            .expect("sent mutex poisoned")
            .push(email.clone());
        Ok(())
    }
}

// ------------------------------------------------------------------ NullMailer

/// Discards all emails. Useful for disabling email sending in environments
/// (e.g. CI) without changing call sites.
#[derive(Default)]
pub struct NullMailer;

#[async_trait]
impl Mailer for NullMailer {
    async fn send(&self, email: &Email) -> Result<(), MailError> {
        email.validate()?;
        Ok(())
    }
}

/// Build a [`BoxedMailer`] from a loaded
/// [`crate::config::MailSettings`] section (#87 wiring, v0.29).
///
/// Backend selection from `s.backend`:
/// - `"console"` (default) → [`ConsoleMailer`]
/// - `"memory"` → [`InMemoryMailer`] (tests / staging snapshots)
/// - `"null"` / `"none"` → [`NullMailer`]
/// - `"smtp"` → falls back to [`ConsoleMailer`] with a warning —
///   `SmtpMailer` is documented but not yet implemented; until
///   that ships, projects that need real SMTP wire it themselves
///   via [`BoxedMailer`]
/// - any other / unset → [`ConsoleMailer`] (dev-friendly default;
///   warn for typos)
///
/// `s.smtp_host` and `s.from_address` are accepted by the section
/// but currently unused at the backend layer — `from_address`
/// belongs on the per-message [`Email::from`] field, not the
/// backend; `smtp_host` lights up when `SmtpMailer` ships.
///
/// ```ignore
/// let cfg = rustango::config::Settings::load_from_env()?;
/// let mailer: rustango::email::BoxedMailer =
///     rustango::email::from_settings(&cfg.mail);
/// ```
#[cfg(feature = "config")]
#[must_use]
pub fn from_settings(s: &crate::config::MailSettings) -> BoxedMailer {
    match s.backend.as_deref() {
        Some("smtp") => {
            tracing::warn!(
                target: "rustango::email",
                "mail.backend = \"smtp\" but SmtpMailer isn't implemented yet; falling back to ConsoleMailer. \
                 Wire your own BoxedMailer in the meantime.",
            );
            Arc::new(ConsoleMailer)
        }
        Some("memory") => Arc::new(InMemoryMailer::new()),
        Some("null" | "none") => Arc::new(NullMailer),
        Some("console") | None => Arc::new(ConsoleMailer),
        Some(other) => {
            tracing::warn!(
                target: "rustango::email",
                backend = %other,
                "unknown mail.backend value; falling back to ConsoleMailer",
            );
            Arc::new(ConsoleMailer)
        }
    }
}

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

    #[tokio::test]
    async fn email_builder_chains() {
        let e = Email::new()
            .to("a@x.com")
            .to("b@x.com")
            .from("noreply@my.app")
            .subject("hi")
            .body("hello");
        assert_eq!(e.to, vec!["a@x.com", "b@x.com"]);
        assert_eq!(e.from.as_deref(), Some("noreply@my.app"));
        assert_eq!(e.subject, "hi");
    }

    #[tokio::test]
    async fn validate_rejects_no_recipients() {
        let e = Email::new().subject("x").body("y");
        assert!(matches!(e.validate(), Err(MailError::InvalidMessage(_))));
    }

    #[tokio::test]
    async fn validate_rejects_empty_subject() {
        let e = Email::new().to("x@y.com").body("z");
        assert!(matches!(e.validate(), Err(MailError::InvalidMessage(_))));
    }

    #[tokio::test]
    async fn in_memory_mailer_captures_sent() {
        let m = InMemoryMailer::new();
        m.send(&Email::new().to("a@x").subject("s").body("b"))
            .await
            .unwrap();
        m.send(&Email::new().to("b@x").subject("s2").body("b2"))
            .await
            .unwrap();
        assert_eq!(m.count(), 2);
        assert_eq!(m.sent()[0].to, vec!["a@x"]);
        m.clear();
        assert_eq!(m.count(), 0);
    }

    #[tokio::test]
    async fn null_mailer_succeeds_silently() {
        let m = NullMailer;
        m.send(&Email::new().to("x@y").subject("s").body("b"))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn null_mailer_still_validates() {
        let m = NullMailer;
        let result = m.send(&Email::new().subject("s")).await;
        assert!(result.is_err());
    }

    // ---- #87 wiring: from_settings ----

    /// Memory backend captures sends so tests can assert on them.
    /// Other backends would either print to stdout or no-op, so
    /// memory is the easiest to exercise here.
    #[cfg(feature = "config")]
    #[tokio::test]
    async fn from_settings_memory_backend_captures_send() {
        let mut s = crate::config::MailSettings::default();
        s.backend = Some("memory".into());
        let m = from_settings(&s);
        let email = Email::new()
            .to("a@x.com")
            .from("noreply@x.com")
            .subject("hi")
            .body("body");
        m.send(&email).await.expect("send ok");
        // Memory backend wraps an Arc<Mutex<Vec<Email>>>; we don't
        // expose it here, but the round-trip not erroring confirms
        // the right backend was selected (NullMailer would also
        // succeed; ConsoleMailer would print). See the dedicated
        // memory_mailer_records_send test for the storage assertion.
    }

    /// Null backend silently drops, even on a valid email.
    #[cfg(feature = "config")]
    #[tokio::test]
    async fn from_settings_null_backend_drops_send() {
        let mut s = crate::config::MailSettings::default();
        s.backend = Some("null".into());
        let m = from_settings(&s);
        let email = Email::new()
            .to("a@x.com")
            .from("noreply@x.com")
            .subject("hi")
            .body("body");
        m.send(&email)
            .await
            .expect("null backend never errors on valid email");
    }

    /// Unknown / unset backend falls back to ConsoleMailer (which
    /// prints — we just check the call succeeds; capturing stdout
    /// in a unit test would race with parallel runners).
    #[cfg(feature = "config")]
    #[tokio::test]
    async fn from_settings_unset_falls_back_to_console() {
        let s = crate::config::MailSettings::default();
        let m = from_settings(&s);
        let email = Email::new()
            .to("a@x.com")
            .from("noreply@x.com")
            .subject("hi")
            .body("body");
        m.send(&email).await.expect("console mailer ok");
    }

    /// SMTP backend warns + falls back to ConsoleMailer until
    /// SmtpMailer ships. Send-call still succeeds — the fallback
    /// is fail-safe so apps don't refuse to boot.
    #[cfg(feature = "config")]
    #[tokio::test]
    async fn from_settings_smtp_falls_back_until_implemented() {
        let mut s = crate::config::MailSettings::default();
        s.backend = Some("smtp".into());
        s.smtp_host = Some("mail.example.com".into());
        let m = from_settings(&s);
        // Same as the unset test — works because the fallback is
        // ConsoleMailer.
        let email = Email::new()
            .to("a@x.com")
            .from("noreply@x.com")
            .subject("hi")
            .body("body");
        m.send(&email).await.expect("smtp fallback to console ok");
    }
}