Skip to main content

renox_core/
mail.rs

1//! Sending email: SMTP in production, the log or memory in development and
2//! tests, HTML templates with a text version, and a preview page.
3//!
4//! ```
5//! # use renox::prelude::*;
6//! # async fn demo(state: AppState, order: renox::serde_json::Value) -> Result {
7//! let mail = state.mail_view("ben@example.com", "Your receipt", "mail/receipt", context! { order })?;
8//! state.mailer.send(mail.clone()).await?;   // now
9//! state.queue_mail(mail).await?;            // through the queue, with retries
10//! # Ok(()) }
11//! ```
12//!
13//! `MAIL_MAILER` picks the driver: `smtp` (`MAIL_HOST`, `MAIL_PORT`,
14//! `MAIL_USERNAME`, `MAIL_PASSWORD`, `MAIL_ENCRYPTION` = `tls`, `starttls` or
15//! `none`), `log` (the default: messages go to the server log) or `memory`
16//! (for tests: `kernel.mailer().sent()`). With `APP_DEBUG` on, the last 50
17//! messages are listed at `/_renox/mail`.
18
19use std::collections::VecDeque;
20use std::sync::{Arc, Mutex};
21
22use anyhow::Context;
23use axum::Router;
24use axum::extract::{Path, State};
25use axum::response::Html;
26use axum::routing::get;
27use lettre::message::header::ContentType;
28use lettre::message::{Mailbox, MultiPart};
29use lettre::transport::smtp::authentication::Credentials;
30use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
31use serde::{Deserialize, Serialize};
32
33use crate::db::{DateTime, now};
34use crate::queue::{Job, JobContext};
35use crate::{AppState, Config, Error, Result, context};
36
37/// How many sent messages the preview page keeps.
38const OUTBOX: usize = 50;
39
40/// One email message. `html` is optional; `text` is always sent.
41///
42/// ```
43/// # use renox::mail::Mail;
44/// let pdf: Vec<u8> = b"%PDF-1.7 ...".to_vec();
45/// let mail = Mail::new("ben@example.com", "Invoice INV-001", "Your invoice is attached.")
46///     .also_to("finance@example.com")
47///     .cc("sales@example.com")
48///     .bcc("archive@example.com")
49///     .reply_to("Coffee Shop <hello@shop.example>")
50///     .from("Coffee Shop Billing <billing@shop.example>") // instead of MAIL_FROM_*
51///     .attach("INV-001.pdf", "application/pdf", pdf);
52/// ```
53///
54/// Addresses are `a@b.c` or `Name <a@b.c>`; an invalid one fails the send
55/// (and a queued mail isn't retried for it).
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
57#[non_exhaustive]
58pub struct Mail {
59    /// Recipients.
60    pub to: Vec<String>,
61    /// The subject line.
62    pub subject: String,
63    /// The plain-text body.
64    pub text: String,
65    /// An HTML body, sent next to `text` when set.
66    #[serde(default)]
67    pub html: Option<String>,
68    /// Carbon-copy recipients.
69    #[serde(default)]
70    pub cc: Vec<String>,
71    /// Blind-carbon-copy recipients.
72    #[serde(default)]
73    pub bcc: Vec<String>,
74    /// The address replies go to.
75    #[serde(default)]
76    pub reply_to: Option<String>,
77    /// Sender instead of `MAIL_FROM_ADDRESS` / `MAIL_FROM_NAME`.
78    #[serde(default)]
79    pub from: Option<String>,
80    /// Files sent with the mail.
81    #[serde(default)]
82    pub attachments: Vec<Attachment>,
83}
84
85/// The inline colours `Mail::theme` replaces; they match
86/// `views/mail/button.html` and `components.html` (a test checks it).
87const MAIL_BUTTON_COLORS: &str = "background:#1c1917;color:#ffffff;";
88const MAIL_PANEL_STRIPE: &str = "border-left:4px solid #1c1917;";
89
90/// A file sent with a mail.
91#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
92#[non_exhaustive]
93pub struct Attachment {
94    /// The file name the recipient sees, e.g. `INV-001.pdf`.
95    pub filename: String,
96    /// e.g. `application/pdf`.
97    pub content_type: String,
98    /// Stored as base64 when the mail is queued.
99    #[serde(with = "base64_bytes")]
100    pub data: Vec<u8>,
101}
102
103mod base64_bytes {
104    use base64::Engine;
105    use base64::engine::general_purpose::STANDARD;
106    use serde::{Deserialize, Deserializer, Serializer};
107
108    pub fn serialize<S: Serializer>(data: &[u8], s: S) -> Result<S::Ok, S::Error> {
109        s.serialize_str(&STANDARD.encode(data))
110    }
111
112    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
113        let text = String::deserialize(d)?;
114        STANDARD.decode(text).map_err(serde::de::Error::custom)
115    }
116}
117
118impl Mail {
119    /// A mail to `to` with this subject and plain-text body.
120    pub fn new(to: impl Into<String>, subject: impl Into<String>, text: impl Into<String>) -> Self {
121        Self {
122            to: vec![to.into()],
123            subject: subject.into(),
124            text: text.into(),
125            html: None,
126            cc: Vec::new(),
127            bcc: Vec::new(),
128            reply_to: None,
129            from: None,
130            attachments: Vec::new(),
131        }
132    }
133
134    /// Adds an HTML body; `text` is still sent as the plain alternative.
135    pub fn html(mut self, html: impl Into<String>) -> Self {
136        self.html = Some(html.into());
137        self
138    }
139
140    /// Another recipient.
141    pub fn also_to(mut self, address: impl Into<String>) -> Self {
142        self.to.push(address.into());
143        self
144    }
145
146    /// Adds a carbon-copy recipient.
147    pub fn cc(mut self, address: impl Into<String>) -> Self {
148        self.cc.push(address.into());
149        self
150    }
151
152    /// Adds a blind-carbon-copy recipient.
153    pub fn bcc(mut self, address: impl Into<String>) -> Self {
154        self.bcc.push(address.into());
155        self
156    }
157
158    /// Where replies go.
159    pub fn reply_to(mut self, address: impl Into<String>) -> Self {
160        self.reply_to = Some(address.into());
161        self
162    }
163
164    /// Sends as `address` instead of `MAIL_FROM_ADDRESS` / `MAIL_FROM_NAME`.
165    pub fn from(mut self, address: impl Into<String>) -> Self {
166        self.from = Some(address.into());
167        self
168    }
169
170    /// Attaches `data` as a file named `filename` of type `content_type`.
171    pub fn attach(
172        mut self,
173        filename: impl Into<String>,
174        content_type: impl Into<String>,
175        data: impl Into<Vec<u8>>,
176    ) -> Self {
177        self.attachments.push(Attachment {
178            filename: filename.into(),
179            content_type: content_type.into(),
180            data: data.into(),
181        });
182        self
183    }
184
185    /// Attaches a calendar file ([`calendar::Ics`](crate::calendar::Ics)) as
186    /// `invite.ics` (`cancellation.ics` when it cancels), with the content
187    /// type `text/calendar; method=REQUEST; charset=UTF-8` (the method of the
188    /// file), so mail clients offer to add it to the calendar.
189    ///
190    /// ```
191    /// # use renox::calendar::{Event, Ics};
192    /// # use renox::chrono::{TimeZone, Utc};
193    /// # use renox::mail::Mail;
194    /// # let at = Utc.with_ymd_and_hms(2026, 11, 3, 9, 0, 0).unwrap();
195    /// let ics = Ics::new("-//Acme//Bookings//EN").event(
196    ///     Event::new("booking-42@acme.test", at, at + renox::chrono::Duration::hours(1))
197    ///         .summary("Service at Acme")
198    ///         .attendee("ben@example.com"),
199    /// );
200    /// let mail = Mail::new("ben@example.com", "Your booking", "See you.").attach_ics(&ics);
201    /// assert_eq!(mail.attachments[0].filename, "invite.ics");
202    /// ```
203    pub fn attach_ics(self, ics: &crate::calendar::Ics) -> Self {
204        let name = if ics.effective_method() == crate::calendar::Method::Cancel {
205            "cancellation.ics"
206        } else {
207            "invite.ics"
208        };
209        self.attach(name, ics.content_type(), ics.to_bytes())
210    }
211
212    /// Applies a brand [`Theme`](crate::theme::Theme) to the HTML body: the
213    /// `button` background and text colour and the `panel` stripe of
214    /// `renox/mail/components.html` take the theme's light `--rx-accent` and
215    /// `--rx-on-accent`. The colours are written into the HTML now, so a mail
216    /// queued afterwards needs no theme at send time. Call it after
217    /// [`AppState::mail_view`]; a mail without an HTML body is unchanged.
218    ///
219    /// ```
220    /// use renox::mail::Mail;
221    /// use renox::theme::{Brand, Theme};
222    ///
223    /// let theme = Theme::from_brand(&Brand::new("#1E3A5F")).unwrap();
224    /// let html = r#"<a style="background:#1c1917;color:#ffffff;">Pay</a>"#;
225    /// let mail = Mail::new("ana@example.com", "Hi", "Hi").html(html).theme(&theme);
226    /// assert!(!mail.html.unwrap().contains("#1c1917"));
227    /// ```
228    pub fn theme(mut self, theme: &crate::theme::Theme) -> Self {
229        let tokens = theme.tokens();
230        if let (Some(html), Some(accent), Some(on_accent)) = (
231            self.html.as_mut(),
232            tokens.get("--rx-accent"),
233            tokens.get("--rx-on-accent"),
234        ) {
235            *html = html
236                .replace(
237                    MAIL_BUTTON_COLORS,
238                    &format!("background:{accent};color:{on_accent};"),
239                )
240                .replace(
241                    MAIL_PANEL_STRIPE,
242                    &format!("border-left:4px solid {accent};"),
243                );
244        }
245        self
246    }
247
248    /// Whether `address` is among `to`, `cc` or `bcc`.
249    pub fn is_for(&self, address: &str) -> bool {
250        self.to
251            .iter()
252            .chain(&self.cc)
253            .chain(&self.bcc)
254            .any(|a| a == address || a.ends_with(&format!("<{address}>")))
255    }
256}
257
258setting_enum! {
259    /// How mail is sent, from `MAIL_MAILER`.
260    pub enum MailDriver ("MAIL_MAILER") {
261        /// Through an SMTP server (`MAIL_HOST`); use it in production.
262        Smtp = "smtp",
263        /// Written to the server log; nothing leaves the machine (the default).
264        Log = "log",
265        /// Kept in memory, for tests (`app.sent_mail()`).
266        Memory = "memory",
267    }
268}
269
270setting_enum! {
271    /// How the SMTP connection is secured, from `MAIL_ENCRYPTION`.
272    pub enum MailEncryption ("MAIL_ENCRYPTION") {
273        /// TLS from the start (usually port 465).
274        Tls = "tls",
275        /// Plain, upgraded with STARTTLS (usually port 587; the default).
276        StartTls = "starttls",
277        /// Not encrypted: a local test server such as Mailpit only.
278        None = "none",
279    }
280}
281
282/// Mail settings, from `MAIL_*`.
283#[derive(Clone)]
284#[non_exhaustive]
285pub struct MailConfig {
286    /// How mail is sent: SMTP, the log or memory.
287    pub mailer: MailDriver,
288    /// SMTP server, from `MAIL_HOST` (default `localhost`).
289    pub host: String,
290    /// SMTP port, from `MAIL_PORT`; `None` uses the encryption's usual port.
291    pub port: Option<u16>,
292    /// SMTP user name, from `MAIL_USERNAME`.
293    pub username: Option<String>,
294    /// SMTP password, from `MAIL_PASSWORD`.
295    pub password: Option<String>,
296    /// `tls` (usually port 465), `starttls` (587) or `none` (e.g. Mailpit on 1025).
297    pub encryption: MailEncryption,
298    /// Sender address, from `MAIL_FROM_ADDRESS` (default `hello@example.com`).
299    pub from_address: String,
300    /// Sender name, from `MAIL_FROM_NAME`.
301    pub from_name: Option<String>,
302    /// How long sending one mail over SMTP may take, from `MAIL_TIMEOUT` in
303    /// seconds (default 10).
304    pub timeout: std::time::Duration,
305    /// Mailers (`App::mailer` names) to try in order when this one fails,
306    /// from `MAIL_FAILOVER` (comma-separated), e.g. `backup` for a second
307    /// SMTP provider.
308    pub failover: Vec<String>,
309}
310
311impl std::fmt::Debug for MailConfig {
312    // Secrets show as `[hidden]`, so a logged config doesn't leak them.
313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314        f.debug_struct("MailConfig")
315            .field("mailer", &self.mailer)
316            .field("host", &self.host)
317            .field("port", &self.port)
318            .field("username", &self.username)
319            .field("password", &self.password.as_ref().map(|_| "[hidden]"))
320            .field("encryption", &self.encryption)
321            .field("from_address", &self.from_address)
322            .field("from_name", &self.from_name)
323            .field("timeout", &self.timeout)
324            .field("failover", &self.failover)
325            .finish()
326    }
327}
328
329impl Default for MailConfig {
330    fn default() -> Self {
331        Self {
332            mailer: MailDriver::Log,
333            host: "localhost".into(),
334            port: None,
335            username: None,
336            password: None,
337            encryption: MailEncryption::StartTls,
338            from_address: "hello@example.com".into(),
339            timeout: std::time::Duration::from_secs(10),
340            from_name: None,
341            failover: Vec::new(),
342        }
343    }
344}
345
346impl MailConfig {
347    /// A mailer's settings from variables starting with `prefix`, for
348    /// [`App::mailer`](crate::App::mailer): `<PREFIX>_MAILER` (`smtp`,
349    /// `log` or `memory`; default: the app's `MAIL_MAILER`, so it logs
350    /// while developing and keeps mail in memory in tests), `<PREFIX>_HOST`, `_PORT`,
351    /// `_USERNAME`, `_PASSWORD`, `_ENCRYPTION`, `_TIMEOUT` (seconds), and
352    /// `<PREFIX>_FROM_ADDRESS` / `_FROM_NAME`, which fall back to the
353    /// app's `MAIL_FROM_*`. A value that doesn't fit (an unknown driver, a
354    /// port that isn't a number) is an error naming the variable, and the
355    /// app doesn't boot.
356    pub fn from_env(config: &Config, prefix: &str) -> crate::Result<Self> {
357        let prefix = prefix.trim_end_matches('_').to_ascii_uppercase();
358        let name = |name: &str| format!("{prefix}_{name}");
359        let var = |key: &str| config.var(&name(key));
360        let number = |key: &str| -> anyhow::Result<Option<u64>> {
361            var(key)
362                .map(|value| {
363                    value.trim().parse::<u64>().map_err(|_| {
364                        anyhow::anyhow!("{} must be a number, got `{value}`", name(key))
365                    })
366                })
367                .transpose()
368        };
369        let defaults = Self::default();
370        let port = number("PORT")?
371            .map(|p| {
372                u16::try_from(p).map_err(|_| anyhow::anyhow!("{} is not a port", name("PORT")))
373            })
374            .transpose()?;
375        Ok(Self {
376            mailer: var("MAILER")
377                .map(|v| MailDriver::parse_as(&v, &name("MAILER")))
378                .transpose()?
379                .unwrap_or(config.mail.mailer),
380            host: var("HOST").unwrap_or(defaults.host),
381            port,
382            username: var("USERNAME"),
383            password: var("PASSWORD"),
384            encryption: var("ENCRYPTION")
385                .map(|v| MailEncryption::parse_as(&v, &name("ENCRYPTION")))
386                .transpose()?
387                .unwrap_or(defaults.encryption),
388            from_address: var("FROM_ADDRESS").unwrap_or_else(|| config.mail.from_address.clone()),
389            from_name: var("FROM_NAME").or_else(|| config.mail.from_name.clone()),
390            timeout: number("TIMEOUT")?.map_or(defaults.timeout, std::time::Duration::from_secs),
391            failover: Vec::new(),
392        })
393    }
394}
395
396#[derive(Clone)]
397enum Driver {
398    Log,
399    Memory,
400    Smtp {
401        transport: AsyncSmtpTransport<Tokio1Executor>,
402        from: Mailbox,
403        timeout: std::time::Duration,
404    },
405}
406
407#[derive(Debug, Clone, Serialize)]
408struct Sent {
409    id: u64,
410    at: DateTime,
411    mail: Mail,
412}
413
414/// Sends mail with the configured driver and remembers recent messages for
415/// the preview page and tests.
416#[derive(Clone)]
417pub struct Mailer {
418    driver: Driver,
419    /// Mailers tried in order when `driver` fails (`MAIL_FAILOVER`).
420    failover: Vec<(String, Driver)>,
421    outbox: Arc<Mutex<(u64, VecDeque<Sent>)>>,
422    /// The memory driver keeps everything; others keep the last `OUTBOX` in debug.
423    keep: Option<usize>,
424}
425
426impl Mailer {
427    pub(crate) fn from_config(config: &Config) -> anyhow::Result<Self> {
428        Self::open(&config.mail, config)
429    }
430
431    /// A mailer from `mail`.
432    pub(crate) fn open(mail: &MailConfig, config: &Config) -> anyhow::Result<Self> {
433        let (driver, keep) = match mail.mailer {
434            MailDriver::Log => (Driver::Log, config.debug.then_some(OUTBOX)),
435            MailDriver::Memory => (Driver::Memory, Some(usize::MAX)),
436            MailDriver::Smtp => (smtp(mail, &config.name)?, config.debug.then_some(OUTBOX)),
437        };
438        Ok(Self {
439            driver,
440            failover: Vec::new(),
441            outbox: Arc::default(),
442            keep,
443        })
444    }
445
446    /// Tries `others` in order when this mailer fails.
447    pub(crate) fn with_failover(mut self, others: Vec<(String, Mailer)>) -> Self {
448        self.failover = others
449            .into_iter()
450            .map(|(name, mailer)| (name, mailer.driver))
451            .collect();
452        self
453    }
454
455    /// Sends `mail` through the configured driver (the `log` and `memory`
456    /// drivers only record it). When it fails and `MAIL_FAILOVER` names
457    /// other mailers, they're tried in order; a mail that can't be sent at
458    /// all (a bad address) isn't handed on.
459    pub async fn send(&self, mail: Mail) -> Result {
460        if let Err(mut last) = deliver(&self.driver, &mail).await {
461            if last.is_permanent() || self.failover.is_empty() {
462                return Err(last);
463            }
464            let mut sent = false;
465            for (name, driver) in &self.failover {
466                tracing::warn!(error = ?last, mailer = %name, "sending mail failed; trying the next mailer");
467                match deliver(driver, &mail).await {
468                    Ok(()) => {
469                        sent = true;
470                        break;
471                    }
472                    Err(err) => last = err,
473                }
474            }
475            if !sent {
476                return Err(last);
477            }
478        }
479        self.remember(mail);
480        Ok(())
481    }
482
483    fn remember(&self, mail: Mail) {
484        let Some(keep) = self.keep else { return };
485        let mut outbox = self.outbox.lock().unwrap_or_else(|e| e.into_inner());
486        outbox.0 += 1;
487        let id = outbox.0;
488        outbox.1.push_back(Sent {
489            id,
490            at: now(),
491            mail,
492        });
493        while outbox.1.len() > keep {
494            outbox.1.pop_front();
495        }
496    }
497
498    /// Messages sent so far that the mailer kept: all of them with the
499    /// `memory` driver, the last 50 with `APP_DEBUG` on.
500    pub fn sent(&self) -> Vec<Mail> {
501        let outbox = self.outbox.lock().unwrap_or_else(|e| e.into_inner());
502        outbox.1.iter().map(|s| s.mail.clone()).collect()
503    }
504
505    fn kept(&self) -> Vec<Sent> {
506        self.outbox
507            .lock()
508            .unwrap_or_else(|e| e.into_inner())
509            .1
510            .iter()
511            .cloned()
512            .collect()
513    }
514}
515
516/// Hands `mail` to one driver.
517async fn deliver(driver: &Driver, mail: &Mail) -> Result {
518    match driver {
519        Driver::Log => tracing::info!(
520            "mail (log driver)\nTo: {}\nSubject: {}\n\n{}\n",
521            mail.to.join(", "),
522            mail.subject,
523            mail.text
524        ),
525        Driver::Memory => {}
526        Driver::Smtp {
527            transport,
528            from,
529            timeout,
530        } => {
531            let message = message(from, mail)?;
532            // lettre's own timeout doesn't cover a server that accepts the
533            // connection and then says nothing.
534            tokio::time::timeout(*timeout, transport.send(message))
535                .await
536                .map_err(|_| anyhow::anyhow!("no answer from the SMTP server in {timeout:?}"))
537                .and_then(|sent| sent.map_err(anyhow::Error::from))
538                .with_context(|| format!("sending mail to {}", mail.to.join(", ")))?;
539        }
540    }
541    Ok(())
542}
543
544fn smtp(mail: &MailConfig, app_name: &str) -> anyhow::Result<Driver> {
545    let mut builder = match mail.encryption {
546        MailEncryption::Tls => AsyncSmtpTransport::<Tokio1Executor>::relay(&mail.host)?,
547        MailEncryption::StartTls => {
548            AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&mail.host)?
549        }
550        MailEncryption::None => AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&mail.host),
551    };
552    if let Some(port) = mail.port {
553        builder = builder.port(port);
554    }
555    builder = builder.timeout(Some(mail.timeout));
556    if let (Some(user), Some(password)) = (&mail.username, &mail.password) {
557        builder = builder.credentials(Credentials::new(user.clone(), password.clone()));
558    }
559    let name = mail
560        .from_name
561        .clone()
562        .unwrap_or_else(|| app_name.to_owned());
563    let address = mail.from_address.parse().with_context(|| {
564        format!(
565            "MAIL_FROM_ADDRESS `{}` is not an email address",
566            mail.from_address
567        )
568    })?;
569    Ok(Driver::Smtp {
570        transport: builder.build(),
571        from: Mailbox::new(Some(name), address),
572        timeout: mail.timeout,
573    })
574}
575
576fn mailbox(address: &str) -> Result<Mailbox> {
577    address.trim().parse().map_err(|err| {
578        Error::permanent(
579            anyhow::Error::new(err).context(format!("`{address}` is not an email address")),
580        )
581    })
582}
583
584fn message(from: &Mailbox, mail: &Mail) -> Result<Message> {
585    use lettre::message::{Attachment as Part, SinglePart};
586
587    if mail.to.is_empty() {
588        return Err(Error::permanent(anyhow::anyhow!(
589            "the mail has no recipient"
590        )));
591    }
592    let from = match &mail.from {
593        Some(address) => mailbox(address)?,
594        None => from.clone(),
595    };
596    let mut builder = Message::builder().from(from).subject(mail.subject.clone());
597    for address in &mail.to {
598        builder = builder.to(mailbox(address)?);
599    }
600    for address in &mail.cc {
601        builder = builder.cc(mailbox(address)?);
602    }
603    for address in &mail.bcc {
604        builder = builder.bcc(mailbox(address)?);
605    }
606    if let Some(address) = &mail.reply_to {
607        builder = builder.reply_to(mailbox(address)?);
608    }
609    let body = match &mail.html {
610        Some(html) => MultiPart::alternative_plain_html(mail.text.clone(), html.clone()),
611        None => MultiPart::mixed().singlepart(
612            SinglePart::builder()
613                .header(ContentType::TEXT_PLAIN)
614                .body(mail.text.clone()),
615        ),
616    };
617    let message = if mail.attachments.is_empty() {
618        match &mail.html {
619            Some(_) => builder.multipart(body),
620            None => builder
621                .header(ContentType::TEXT_PLAIN)
622                .body(mail.text.clone()),
623        }
624    } else {
625        let mut mixed = MultiPart::mixed().multipart(body);
626        for file in &mail.attachments {
627            let content_type = ContentType::parse(&file.content_type).map_err(|err| {
628                Error::permanent(anyhow::anyhow!(
629                    "attachment `{}`: `{}` is not a content type ({err})",
630                    file.filename,
631                    file.content_type
632                ))
633            })?;
634            mixed = mixed
635                .singlepart(Part::new(file.filename.clone()).body(file.data.clone(), content_type));
636        }
637        builder.multipart(mixed)
638    };
639    Ok(message.map_err(anyhow::Error::from)?)
640}
641
642/// Sends a mail from the queue; see `AppState::queue_mail`.
643#[derive(Serialize, Deserialize)]
644pub(crate) struct SendMail {
645    // Flattened, so mail queued before limits existed still decodes.
646    #[serde(flatten)]
647    mail: Mail,
648    /// `App::mailer_rate_limit("default", …)` when this was queued.
649    #[serde(default, skip_serializing_if = "Option::is_none")]
650    limit: Option<crate::queue::Limit>,
651}
652
653impl Job for SendMail {
654    const NAME: &'static str = "renox.send-mail";
655    const MAX_ATTEMPTS: u32 = 5;
656
657    fn middleware(&self) -> Vec<crate::queue::Middleware> {
658        crate::queue::Limit::middleware(self.limit, "mailer:default".to_owned())
659    }
660
661    async fn handle(self, ctx: JobContext) -> Result {
662        ctx.state.mailer.send(self.mail).await
663    }
664}
665
666/// Sends a mail from the queue through a named mailer; see
667/// `AppState::queue_mail_via`.
668#[derive(Serialize, Deserialize)]
669pub(crate) struct SendMailVia {
670    pub mailer: String,
671    pub mail: Mail,
672    /// `App::mailer_rate_limit` when this was queued.
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub limit: Option<crate::queue::Limit>,
675}
676
677impl Job for SendMailVia {
678    const NAME: &'static str = "renox.send-mail-via";
679    const MAX_ATTEMPTS: u32 = 5;
680
681    fn middleware(&self) -> Vec<crate::queue::Middleware> {
682        crate::queue::Limit::middleware(self.limit, format!("mailer:{}", self.mailer))
683    }
684
685    async fn handle(self, ctx: JobContext) -> Result {
686        // A mailer removed since the mail was queued won't come back.
687        let mailer = ctx
688            .state
689            .mailer_named(&self.mailer)
690            .map_err(|err| Error::permanent(anyhow::anyhow!("{err:?}")))?;
691        mailer.send(self.mail).await
692    }
693}
694
695impl AppState {
696    /// Renders `{view}.html` into a mail, with `{view}.txt` as the text
697    /// version when it exists (otherwise text made from the HTML).
698    /// Templates see `app` (`app.locale` and `app.dir`, `"ltr"` or `"rtl"`, too) and `t(key, …)` in the
699    /// [`current_locale`](crate::i18n::current_locale) besides `ctx`, can
700    /// extend `renox/mail/layout.html` and import
701    /// `renox/mail/components.html` (`button`, `panel`, `table`).
702    pub fn mail_view(
703        &self,
704        to: impl Into<String>,
705        subject: impl Into<String>,
706        view: &str,
707        ctx: impl Serialize,
708    ) -> Result<Mail> {
709        let locale = crate::i18n::current_locale(self);
710        let ctx = minijinja::value::merge_maps([
711            minijinja::Value::from_serialize(&ctx),
712            context! {
713                app => context! { name => self.config.name, url => self.config.url, locale => locale, dir => self.direction(&locale).as_str() },
714                t => crate::view::translate_function(self, &locale),
715            },
716        ]);
717        let html = self.views.render(&format!("{view}.html"), &ctx)?;
718        let text = match self.views.render(&format!("{view}.txt"), &ctx) {
719            Ok(text) => text,
720            Err(err) if is_not_found(&err) => html_to_text(&html),
721            Err(err) => return Err(err.into()),
722        };
723        Ok(Mail::new(to, subject, text.trim().to_owned()).html(html))
724    }
725
726    /// `mail_view` in `locale` (the recipient's language).
727    pub fn mail_view_in(
728        &self,
729        locale: &str,
730        to: impl Into<String>,
731        subject: impl Into<String>,
732        view: &str,
733        ctx: impl Serialize,
734    ) -> Result<Mail> {
735        crate::i18n::with_locale(Some(locale), || self.mail_view(to, subject, view, ctx))
736    }
737
738    /// Sends `mail` from a queue worker, retrying up to five times.
739    pub async fn queue_mail(&self, mail: Mail) -> Result<i64> {
740        self.dispatch(SendMail {
741            mail,
742            limit: self.mailer_limits.get("default").copied(),
743        })
744        .await
745    }
746
747    /// A mailer the app added with [`App::mailer`](crate::App::mailer), e.g.
748    /// `state.mailer_named("newsletter")?.send(mail)`; an unknown name is an
749    /// error (500).
750    pub fn mailer_named(&self, name: &str) -> Result<&Mailer> {
751        self.mailers.get(name).ok_or_else(|| {
752            anyhow::anyhow!("no mailer named `{name}`: add it with `App::mailer(\"{name}\", …)`")
753                .into()
754        })
755    }
756
757    /// Like `queue_mail`, through the mailer named `mailer`.
758    pub async fn queue_mail_via(&self, mailer: &str, mail: Mail) -> Result<i64> {
759        self.mailer_named(mailer)?;
760        self.dispatch(SendMailVia {
761            mailer: mailer.to_owned(),
762            mail,
763            limit: self.mailer_limits.get(mailer).copied(),
764        })
765        .await
766    }
767}
768
769fn is_not_found(err: &anyhow::Error) -> bool {
770    err.downcast_ref::<minijinja::Error>()
771        .is_some_and(|e| e.kind() == minijinja::ErrorKind::TemplateNotFound)
772}
773
774/// A readable text version of an HTML mail: tags dropped, blocks separated
775/// by blank lines, table cells by spaces, links written as `text (url)`.
776pub(crate) fn html_to_text(html: &str) -> String {
777    let body = html
778        .find("<body")
779        .and_then(|start| html[start..].find('>').map(|end| start + end + 1))
780        .map_or(html, |start| &html[start..]);
781    let mut out = String::new();
782    let mut href: Option<String> = None;
783    let mut rest = body;
784    while let Some(open) = rest.find('<') {
785        out.push_str(&rest[..open]);
786        let Some(close) = rest[open..].find('>') else {
787            // A `<` that opens no tag: the rest is text (once).
788            rest = &rest[open..];
789            break;
790        };
791        let tag = &rest[open + 1..open + close];
792        let name = tag
793            .trim_start_matches('/')
794            .split(|c: char| c.is_whitespace() || c == '/')
795            .next()
796            .unwrap_or_default()
797            .to_ascii_lowercase();
798        match name.as_str() {
799            "a" if !tag.starts_with('/') => {
800                href = tag
801                    .split("href=\"")
802                    .nth(1)
803                    .and_then(|v| v.split('"').next())
804                    .map(str::to_owned);
805            }
806            "a" => {
807                if let Some(url) = href.take() {
808                    out.push_str(&format!(" ({url})"));
809                }
810            }
811            "style" | "head" | "title" if !tag.starts_with('/') => {
812                let end = format!("</{name}");
813                if let Some(skip) = rest[open..].to_ascii_lowercase().find(&end) {
814                    rest = &rest[open + skip..];
815                    continue;
816                }
817            }
818            "br" | "p" | "div" | "tr" | "li" | "h1" | "h2" | "h3" | "table" => out.push('\n'),
819            "td" | "th" => out.push(' '),
820            _ => {}
821        }
822        rest = &rest[open + close + 1..];
823    }
824    out.push_str(rest);
825    let decoded = out
826        .replace("&nbsp;", " ")
827        .replace("&lt;", "<")
828        .replace("&gt;", ">")
829        .replace("&quot;", "\"")
830        .replace("&#39;", "'")
831        .replace("&#x27;", "'")
832        .replace("&#x2f;", "/")
833        .replace("&amp;", "&");
834    let mut text = String::new();
835    let mut blank = false;
836    for line in decoded
837        .lines()
838        .map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
839    {
840        if line.is_empty() {
841            blank = !text.is_empty();
842            continue;
843        }
844        if blank {
845            text.push('\n');
846            blank = false;
847        }
848        text.push_str(&line);
849        text.push('\n');
850    }
851    text
852}
853
854/// `/_renox/mail`: recently sent messages, in development only.
855pub(crate) fn preview_router() -> Router<AppState> {
856    Router::new()
857        .route("/_renox/mail", get(list))
858        .route("/_renox/mail/{id}", get(show))
859}
860
861fn escape(s: &str) -> String {
862    s.replace('&', "&amp;")
863        .replace('<', "&lt;")
864        .replace('>', "&gt;")
865        .replace('"', "&quot;")
866}
867
868const STYLE: &str = "<style>body{font-family:system-ui,sans-serif;max-width:60rem;margin:2rem auto;padding:0 1rem;color:#222}\
869table{width:100%;border-collapse:collapse}td{padding:.5rem;border-bottom:1px solid #eee}\
870iframe{width:100%;height:32rem;border:1px solid #ddd;border-radius:.5rem}pre{white-space:pre-wrap;background:#f6f6f6;padding:1rem}</style>";
871
872async fn list(State(state): State<AppState>) -> Html<String> {
873    let rows: String = state
874        .mailer
875        .kept()
876        .iter()
877        .rev()
878        .map(|s| {
879            format!(
880                "<tr><td>{}</td><td><a href=\"/_renox/mail/{}\">{}</a></td><td>{}</td></tr>",
881                s.at.format("%H:%M:%S"),
882                s.id,
883                escape(&s.mail.subject),
884                escape(&s.mail.to.join(", "))
885            )
886        })
887        .collect();
888    let rows = if rows.is_empty() {
889        "<tr><td>No mail sent yet.</td></tr>".to_owned()
890    } else {
891        rows
892    };
893    Html(format!(
894        "<!doctype html><meta charset=utf-8><title>Mail · Renox</title>{STYLE}<h1>Sent mail</h1><table>{rows}</table>"
895    ))
896}
897
898async fn show(State(state): State<AppState>, Path(id): Path<u64>) -> Result<Html<String>> {
899    let sent = state
900        .mailer
901        .kept()
902        .into_iter()
903        .find(|s| s.id == id)
904        .ok_or(Error::NotFound)?;
905    let html = sent.mail.html.as_deref().map_or(String::new(), |html| {
906        format!(
907            "<h2>HTML</h2><iframe sandbox srcdoc=\"{}\"></iframe>",
908            escape(html)
909        )
910    });
911    let mut details = format!("<p>To: {}</p>", escape(&sent.mail.to.join(", ")));
912    for (label, list) in [("Cc", &sent.mail.cc), ("Bcc", &sent.mail.bcc)] {
913        if !list.is_empty() {
914            details.push_str(&format!("<p>{label}: {}</p>", escape(&list.join(", "))));
915        }
916    }
917    for (label, value) in [("Reply-To", &sent.mail.reply_to), ("From", &sent.mail.from)] {
918        if let Some(value) = value {
919            details.push_str(&format!("<p>{label}: {}</p>", escape(value)));
920        }
921    }
922    if !sent.mail.attachments.is_empty() {
923        let files: Vec<String> = sent
924            .mail
925            .attachments
926            .iter()
927            .map(|a| {
928                format!(
929                    "{} ({}, {} bytes)",
930                    escape(&a.filename),
931                    escape(&a.content_type),
932                    a.data.len()
933                )
934            })
935            .collect();
936        details.push_str(&format!("<p>Attachments: {}</p>", files.join(", ")));
937    }
938    Ok(Html(format!(
939        "<!doctype html><meta charset=utf-8><title>{subject} · Renox</title>{STYLE}\
940         <p><a href=\"/_renox/mail\">&larr; All mail</a></p><h1>{subject}</h1>{details}{html}\
941         <h2>Text</h2><pre>{text}</pre>",
942        subject = escape(&sent.mail.subject),
943        text = escape(&sent.mail.text),
944    )))
945}
946
947#[cfg(test)]
948mod tests {
949    use super::*;
950
951    #[test]
952    fn theme_colours_the_mail_components_and_survives_queueing() {
953        let components = include_str!("../views/mail/components.html");
954        let button = include_str!("../views/mail/button.html");
955        assert!(components.contains(MAIL_BUTTON_COLORS));
956        assert!(components.contains(MAIL_PANEL_STRIPE));
957        assert!(button.contains(MAIL_BUTTON_COLORS));
958
959        let theme = crate::theme::Theme::from_brand(&crate::theme::Brand::new("#1E3A5F")).unwrap();
960        let tokens = theme.tokens();
961        let html = format!(
962            "<a style=\"x;{MAIL_BUTTON_COLORS}y\">Go</a><td style=\"{MAIL_PANEL_STRIPE}\">"
963        );
964        let mail = Mail::new("a@b.c", "s", "t").html(html).theme(&theme);
965        let html = mail.html.clone().unwrap();
966        assert!(html.contains(&format!(
967            "background:{};color:{};",
968            tokens["--rx-accent"], tokens["--rx-on-accent"]
969        )));
970        assert!(html.contains(&format!("border-left:4px solid {};", tokens["--rx-accent"])));
971        assert!(!html.contains("#1c1917"));
972        // The colours are in the mail itself, so a queued copy keeps them.
973        let queued: Mail = serde_json::from_str(&serde_json::to_string(&mail).unwrap()).unwrap();
974        assert_eq!(queued, mail);
975        // No HTML body: nothing to do.
976        let plain = Mail::new("a@b.c", "s", "t").theme(&theme);
977        assert_eq!(plain.html, None);
978    }
979
980    #[test]
981    fn html_becomes_readable_text() {
982        let html = r#"<html><head><style>p{color:red}</style></head><body>
983            <h1>Hello &amp; welcome</h1><p>Click <a href="https://x.id/a?b=1&amp;c=2">here</a>.</p>
984            <table><tr><td>Total</td><td>$10.00</td></tr></table></body></html>"#;
985        assert_eq!(
986            html_to_text(html),
987            "Hello & welcome\n\nClick here (https://x.id/a?b=1&c=2).\n\nTotal $10.00\n"
988        );
989        // Without a <body>: a style block is skipped, and a title that is
990        // never closed is dropped as a tag.
991        assert_eq!(html_to_text("<style>p{}</style>Hi<p>there"), "Hi\nthere\n");
992        assert_eq!(html_to_text("<title>No end"), "No end\n");
993        // A `<` that opens no tag is text, kept once (it was written twice).
994        assert_eq!(html_to_text("Price < 5"), "Price < 5\n");
995        assert_eq!(html_to_text("<p>a</p>b <c"), "a\nb <c\n");
996    }
997
998    /// The log driver writes the mail to the log; with `APP_DEBUG` on it
999    /// keeps the last 50 for `/_renox/mail`, and none with it off.
1000    #[tokio::test]
1001    async fn the_log_driver_keeps_the_last_fifty_while_debugging() {
1002        let mut config = Config {
1003            debug: true,
1004            ..Config::default()
1005        };
1006        let mail = MailConfig::default();
1007        let mailer = Mailer::open(&mail, &config).unwrap();
1008        for i in 0..OUTBOX + 1 {
1009            mailer
1010                .send(Mail::new("ann@example.com", format!("Mail {i}"), "Hi"))
1011                .await
1012                .unwrap();
1013        }
1014        let sent = mailer.sent();
1015        assert_eq!(sent.len(), OUTBOX);
1016        assert_eq!(sent[0].subject, "Mail 1", "the oldest is gone");
1017
1018        config.debug = false;
1019        let quiet = Mailer::open(&mail, &config).unwrap();
1020        quiet
1021            .send(Mail::new("ann@example.com", "Hi", "Hi"))
1022            .await
1023            .unwrap();
1024        assert!(quiet.sent().is_empty());
1025    }
1026
1027    /// Mails SMTP can't send are permanent errors (no retry), found before
1028    /// connecting: no recipient, an attachment with a bad content type.
1029    #[test]
1030    fn mails_smtp_cant_send_are_permanent_errors() {
1031        let from: Mailbox = "shop@example.com".parse().unwrap();
1032        let mut nobody = Mail::new("ann@example.com", "Hi", "Hi");
1033        nobody.to.clear();
1034        let err = message(&from, &nobody).unwrap_err();
1035        assert!(err.is_permanent());
1036        assert!(format!("{err:?}").contains("the mail has no recipient"));
1037
1038        let odd = Mail::new("ann@example.com", "Hi", "Hi").attach("a.bin", "not a type", vec![1]);
1039        let err = message(&from, &odd).unwrap_err();
1040        assert!(err.is_permanent());
1041        assert!(
1042            format!("{err:?}").contains("is not a content type"),
1043            "{err:?}"
1044        );
1045    }
1046
1047    #[tokio::test]
1048    async fn the_outbox_page_says_when_nothing_was_sent() {
1049        let app = crate::testing::TestApp::new(crate::App::new()).await;
1050        app.get("/_renox/mail")
1051            .await
1052            .assert_ok()
1053            .assert_see("No mail sent yet.");
1054    }
1055}