runique 3.0.2

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
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
//! E-mail client (`lettre`) — SMTP + console backends, async sending, Tera template support.
use lettre::{
    AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor, message::header::ContentType,
    transport::smtp::authentication::Credentials,
};
use std::{env::var, sync::OnceLock};

// ─── Backend ─────────────────────────────────────────────────────────────────

/// Which transport `Email::send()` uses to deliver a message.
#[derive(Debug, Clone, Default)]
pub enum MailerBackend {
    /// Sends over SMTP, using the credentials/host in [`MailerConfig`]. Default.
    #[default]
    Smtp,
    /// Prints the email to stdout instead of sending it — for local dev.
    Console,
}

// ─── Config ──────────────────────────────────────────────────────────────────

/// Global mailer configuration, set once via [`mailer_init`] or
/// [`mailer_init_from_env`] and read by every [`Email::send`] call.
pub static MAILER_CONFIG: OnceLock<MailerConfig> = OnceLock::new();

/// SMTP/console mailer configuration. Build it with [`MailerConfig::from_env`]
/// or construct it directly, then register it with [`mailer_init`].
#[derive(Clone)]
pub struct MailerConfig {
    /// Transport used to deliver emails.
    pub backend: MailerBackend,
    /// SMTP server host (unused for the `Console` backend).
    pub host: String,
    /// SMTP server port (unused for the `Console` backend).
    pub port: u16,
    /// SMTP authentication username (unused for the `Console` backend).
    pub username: String,
    /// SMTP authentication password (unused for the `Console` backend). Never
    /// printed — `Debug` redacts it as `***` to avoid leaking it via logs.
    pub password: String,
    /// `From:` address used on every sent email.
    pub from: String,
    /// Whether to upgrade the SMTP connection with STARTTLS.
    pub starttls: bool,
}

// Debug manuel : ne jamais imprimer le mot de passe SMTP en clair (fuite via logs).
impl std::fmt::Debug for MailerConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MailerConfig")
            .field("backend", &self.backend)
            .field("host", &self.host)
            .field("port", &self.port)
            .field("username", &self.username)
            .field("password", &"***")
            .field("from", &self.from)
            .field("starttls", &self.starttls)
            .finish()
    }
}

impl MailerConfig {
    /// Builds a config from environment variables: `EMAIL_BACKEND` (`"console"`
    /// or `"smtp"`, defaults to `"smtp"`), `SMTP_FROM`, and for the SMTP backend
    /// `SMTP_HOST`/`SMTP_USER`/`SMTP_PASS` (required — returns `None` if any is
    /// missing), plus optional `SMTP_PORT` (default `587`) and `SMTP_STARTTLS`
    /// (default `true`).
    pub fn from_env() -> Option<Self> {
        let backend = match crate::utils::config::env::env_keyword("EMAIL_BACKEND")
            .as_deref()
            .unwrap_or("smtp")
        {
            "console" => MailerBackend::Console,
            _ => MailerBackend::Smtp,
        };

        match backend {
            MailerBackend::Console => Some(Self {
                backend: MailerBackend::Console,
                host: String::new(),
                port: 0,
                username: String::new(),
                password: String::new(),
                from: var("SMTP_FROM").unwrap_or_else(|_| "noreply@localhost".to_string()),
                starttls: false,
            }),
            MailerBackend::Smtp => {
                let host = var("SMTP_HOST").ok()?;
                let username = var("SMTP_USER").ok()?;
                let password = var("SMTP_PASS").ok()?;
                let from = var("SMTP_FROM").unwrap_or_else(|_| username.clone());
                let port = var("SMTP_PORT")
                    .ok()
                    .and_then(|p| p.parse().ok())
                    .unwrap_or(587);
                let starttls = var("SMTP_STARTTLS").map(|v| v == "true").unwrap_or(true);
                Some(Self {
                    backend: MailerBackend::Smtp,
                    host,
                    port,
                    username,
                    password,
                    from,
                    starttls,
                })
            }
        }
    }
}

/// Registers the mailer configuration globally. A no-op if it was already set
/// (e.g. called twice) — the first configuration wins.
pub fn mailer_init(config: MailerConfig) {
    MAILER_CONFIG.set(config).ok();
}

/// Builds a [`MailerConfig`] from environment variables (see
/// [`MailerConfig::from_env`]) and registers it via [`mailer_init`]. Leaves the
/// mailer unconfigured if the required SMTP variables are missing.
pub fn mailer_init_from_env() {
    if let Some(config) = MailerConfig::from_env() {
        mailer_init(config);
    }
}

/// Whether [`mailer_init`] (or [`mailer_init_from_env`]) has been called.
pub fn mailer_configured() -> bool {
    MAILER_CONFIG.get().is_some()
}

// ─── Email builder ────────────────────────────────────────────────────────────

/// Builder for a single outgoing email — chain the setters, then call
/// [`Email::send`]. Requires either [`Email::html`], [`Email::text`], or
/// [`Email::template`] to be called, and the global mailer to be configured
/// (see [`mailer_init`]/[`mailer_init_from_env`]).
pub struct Email {
    to: String,
    subject: String,
    html: Option<String>,
    text: Option<String>,
    reply_to: Option<String>,
}

impl Email {
    /// Starts a new, empty email builder.
    pub fn new() -> Self {
        Self {
            to: String::new(),
            subject: String::new(),
            html: None,
            text: None,
            reply_to: None,
        }
    }

    /// Sets the recipient address.
    pub fn to(mut self, address: impl Into<String>) -> Self {
        self.to = address.into();
        self
    }

    /// Sets the email subject.
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = subject.into();
        self
    }

    /// Sets a raw HTML body directly. For a Tera-rendered body, use
    /// [`Email::template`] instead.
    pub fn html(mut self, body: impl Into<String>) -> Self {
        self.html = Some(body.into());
        self
    }

    /// Sets a plain-text body. Ignored if [`Email::html`]/[`Email::template`]
    /// was also called — `send()` prefers HTML when both are set.
    pub fn text(mut self, body: impl Into<String>) -> Self {
        self.text = Some(body.into());
        self
    }

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

    /// Renders a Tera template with a `tera::Context` and sets it as the HTML body.
    ///
    /// Build the context with the `context!` macro:
    /// ```rust,no_run
    /// # use runique::prelude::Email;
    /// # use runique::context;
    /// # use runique::macros::helper::ContextHelper;
    /// # async fn example(tera: &tera::Tera, user_email: &str, username: &str, confirm_url: &str) -> Result<(), String> {
    /// let ctx = context! { "username" => username, "url" => confirm_url };
    /// Email::new().to(user_email).subject("Bienvenue").template(tera, "emails/welcome.html", ctx.into())?.send().await?;
    /// # Ok(()) }
    /// ```
    pub fn template(
        mut self,
        tera: &tera::Tera,
        template_name: &str,
        ctx: tera::Context,
    ) -> Result<Self, String> {
        let rendered = tera
            .render(template_name, &ctx)
            .map_err(|e| format!("Template error ({template_name}): {e}"))?;
        self.html = Some(rendered);
        Ok(self)
    }

    /// Sends the email through the globally configured backend. Fails if the
    /// mailer isn't configured, if neither an HTML nor a text body was set, or
    /// if the addresses/transport are invalid.
    pub async fn send(self) -> Result<(), String> {
        let config = MAILER_CONFIG.get().ok_or_else(|| {
            if let Some(level) = crate::utils::runique_log::get_log()
                .mailer
                .as_ref()
                .and_then(|m| m.send)
            {
                crate::runique_log!(level, to = %self.to, subject = %self.subject, "send — mailer not configured");
            }
            "Mailer not configured — call .with_mailer_from_env() in the builder or set EMAIL_BACKEND/SMTP_* in .env"
                .to_string()
        })?;

        if self.html.is_none() && self.text.is_none() {
            return Err("Email without content".to_string());
        }

        let backend = match config.backend {
            MailerBackend::Console => "console",
            MailerBackend::Smtp => "smtp",
        };
        if let Some(level) = crate::utils::runique_log::get_log()
            .mailer
            .as_ref()
            .and_then(|m| m.send)
        {
            crate::runique_log!(level, to = %self.to, subject = %self.subject, backend, "send");
        }
        let result = match config.backend {
            MailerBackend::Console => self.send_console(config),
            MailerBackend::Smtp => self.send_smtp(config).await,
        };
        if let Err(ref e) = result
            && let Some(level) = crate::utils::runique_log::get_log()
                .mailer
                .as_ref()
                .and_then(|m| m.send)
        {
            crate::runique_log!(level, error = %e, backend, "send error");
        }
        result
    }

    fn send_console(self, config: &MailerConfig) -> Result<(), String> {
        let body = self
            .html
            .as_deref()
            .or(self.text.as_deref())
            .unwrap_or("(no content)");

        println!(
            "\n{}\n  From:    {}\n  To:      {}\n  Subject: {}{}\n\n{}\n{}",
            "─".repeat(60),
            config.from,
            self.to,
            self.subject,
            self.reply_to
                .as_deref()
                .map(|r| format!("\n  Reply-To: {r}"))
                .unwrap_or_default(),
            body,
            "─".repeat(60),
        );
        Ok(())
    }

    async fn send_smtp(self, config: &MailerConfig) -> Result<(), String> {
        let from = config
            .from
            .parse::<lettre::message::Mailbox>()
            .map_err(|e| format!("Invalid sender address: {e}"))?;

        let to = self
            .to
            .parse::<lettre::message::Mailbox>()
            .map_err(|e| format!("Invalid recipient address: {e}"))?;

        let mut builder = Message::builder().from(from).to(to).subject(self.subject);

        if let Some(reply_to) = &self.reply_to {
            let rt = reply_to
                .parse::<lettre::message::Mailbox>()
                .map_err(|e| format!("Invalid Reply-To: {e}"))?;
            builder = builder.reply_to(rt);
        }

        let message = if let Some(html) = self.html {
            builder
                .header(ContentType::TEXT_HTML)
                .body(html)
                .map_err(|e| format!("Error constructing email: {e}"))?
        } else if let Some(text) = self.text {
            builder
                .header(ContentType::TEXT_PLAIN)
                .body(text)
                .map_err(|e| format!("Error constructing email: {e}"))?
        } else {
            return Err("Email without content".to_string());
        };

        let creds = Credentials::new(config.username.clone(), config.password.clone());

        let transport = if config.starttls {
            AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&config.host)
                .map_err(|e| format!("SMTP connection failed: {e}"))?
                .port(config.port)
                .credentials(creds)
                .build()
        } else {
            AsyncSmtpTransport::<Tokio1Executor>::relay(&config.host)
                .map_err(|e| format!("SMTP connection failed: {e}"))?
                .port(config.port)
                .credentials(creds)
                .build()
        };

        transport
            .send(message)
            .await
            .map_err(|e| format!("Error sending email: {e}"))?;

        Ok(())
    }
}

impl Default for Email {
    fn default() -> Self {
        Self::new()
    }
}

// ─── Shorthand ────────────────────────────────────────────────────────────────

/// Sends a plain-text email in one call.
/// For HTML, templates, or reply-to, use `Email::new()` instead.
pub async fn dispatch_email(to: &str, subject: &str, body: &str) -> Result<(), String> {
    Email::new().to(to).subject(subject).text(body).send().await
}

/// Written from cargo-mutants survivors (2026-10-02).
#[cfg(test)]
mod guarantees {
    use super::*;

    // `from_env` reads the process environment: one test at a time.
    static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

    fn set(vars: &[(&str, Option<&str>)]) {
        for (k, v) in vars {
            match v {
                Some(v) => unsafe { std::env::set_var(k, v) },
                None => unsafe { std::env::remove_var(k) },
            }
        }
    }

    const SMTP_VARS: [&str; 7] = [
        "EMAIL_BACKEND",
        "SMTP_HOST",
        "SMTP_USER",
        "SMTP_PASS",
        "SMTP_FROM",
        "SMTP_PORT",
        "SMTP_STARTTLS",
    ];

    fn clear() {
        set(&SMTP_VARS.map(|k| (k, None)));
    }

    fn smtp_config() -> MailerConfig {
        MailerConfig {
            backend: MailerBackend::Smtp,
            host: "smtp.example".into(),
            port: 587,
            username: "user".into(),
            password: "hunter2-secret".into(),
            from: "noreply@example.com".into(),
            starttls: true,
        }
    }

    #[test]
    fn debug_never_prints_the_smtp_password() {
        let shown = format!("{:?}", smtp_config());
        assert!(
            shown.contains("smtp.example") && shown.contains("***"),
            "{shown}"
        );
        assert!(!shown.contains("hunter2-secret"), "{shown}");
    }

    #[tokio::test]
    async fn from_env_reads_each_backend() {
        let _g = ENV_LOCK.lock().await;
        clear();
        set(&[("EMAIL_BACKEND", Some("console"))]);
        let console = MailerConfig::from_env().expect("console needs no credentials");
        assert!(matches!(console.backend, MailerBackend::Console));
        assert_eq!(console.from, "noreply@localhost");

        set(&[
            ("EMAIL_BACKEND", Some("smtp")),
            ("SMTP_HOST", Some("smtp.example")),
        ]);
        assert!(
            MailerConfig::from_env().is_none(),
            "smtp without credentials"
        );
        set(&[
            ("SMTP_USER", Some("user@example.com")),
            ("SMTP_PASS", Some("pw")),
        ]);
        let smtp = MailerConfig::from_env().expect("smtp");
        assert!(matches!(smtp.backend, MailerBackend::Smtp));
        assert_eq!(
            smtp.from, "user@example.com",
            "From defaults to the SMTP user"
        );
        assert_eq!(smtp.port, 587);
        assert!(smtp.starttls);

        set(&[("SMTP_PORT", Some("465")), ("SMTP_STARTTLS", Some("false"))]);
        let smtps = MailerConfig::from_env().unwrap();
        assert_eq!(smtps.port, 465);
        assert!(!smtps.starttls);
        clear();
    }

    #[test]
    fn builders_set_what_they_name() {
        let mut tera = tera::Tera::default();
        tera.add_raw_template("mail.html", "Bonjour {{ name }}")
            .unwrap();
        let mut ctx = tera::Context::new();
        ctx.insert("name", "Ada");
        let email = Email::new()
            .to("ada@example.com")
            .subject("Sujet")
            .reply_to("support@example.com")
            .template(&tera, "mail.html", ctx)
            .unwrap();
        assert_eq!(email.to, "ada@example.com");
        assert_eq!(email.subject, "Sujet");
        assert_eq!(email.reply_to.as_deref(), Some("support@example.com"));
        assert_eq!(email.html.as_deref(), Some("Bonjour Ada"));
        assert!(
            Email::new()
                .template(&tera, "missing.html", tera::Context::new())
                .is_err()
        );
    }

    #[tokio::test]
    async fn smtp_refuses_invalid_addresses_before_connecting() {
        let ok = || Email::new().to("ada@example.com").subject("s").text("b");
        let err = |e: Email| async move { e.send_smtp(&smtp_config()).await.unwrap_err() };
        assert!(err(ok().to("not an address")).await.contains("recipient"));
        assert!(err(ok().reply_to("nope")).await.contains("Reply-To"));
        let mut bad_from = smtp_config();
        bad_from.from = "nope".into();
        assert!(
            ok().send_smtp(&bad_from)
                .await
                .unwrap_err()
                .contains("sender")
        );
        let empty = Email::new().to("ada@example.com").subject("s");
        assert!(
            empty
                .send_smtp(&smtp_config())
                .await
                .unwrap_err()
                .contains("content")
        );
    }

    #[tokio::test]
    async fn sending_needs_a_configured_mailer() {
        let _g = ENV_LOCK.lock().await;
        // The global config is set at most once per process: only this test sets it.
        if !mailer_configured() {
            assert!(dispatch_email("ada@example.com", "s", "b").await.is_err());
            clear();
            set(&[("EMAIL_BACKEND", Some("console"))]);
            mailer_init_from_env();
            clear();
        }
        assert!(mailer_configured());
        assert!(dispatch_email("ada@example.com", "s", "b").await.is_ok());
    }
}