Skip to main content

sunday_slate/mail/
mod.rs

1use std::sync::{Arc, Mutex};
2
3use crate::Config;
4use lettre::AsyncTransport;
5
6pub mod capture;
7pub mod render;
8pub mod transport;
9
10/// A fully rendered email, ready for delivery or capture.
11#[derive(Debug, Clone)]
12pub struct OutgoingEmail {
13    pub from: String,
14    pub to: String,
15    pub subject: String,
16    pub html: String,
17    pub text: String,
18}
19
20/// Errors during mail operations.
21#[derive(Debug, thiserror::Error)]
22pub enum MailError {
23    #[error("template render failed: {0}")]
24    Render(#[from] askama::Error),
25
26    #[error("invalid email address: {0}")]
27    Address(#[from] lettre::address::AddressError),
28
29    #[error("failed to build TLS parameters: {0}")]
30    Tls(lettre::transport::smtp::Error),
31
32    #[error("failed to build email: {0}")]
33    Build(#[from] lettre::error::Error),
34
35    #[error("SMTP send failed: {0}")]
36    Send(#[from] lettre::transport::smtp::Error),
37}
38
39/// Delivery mechanism. Cloneable so it can live in `AppState`.
40#[derive(Clone)]
41pub enum Mailer {
42    Smtp {
43        transport: lettre::AsyncSmtpTransport<lettre::Tokio1Executor>,
44        default_from: String,
45    },
46    Capture(Arc<Mutex<Vec<OutgoingEmail>>>, String),
47}
48
49impl Mailer {
50    /// Capture mailer with the given `From:` and an empty store.
51    /// Clones share the underlying store.
52    pub fn capture(from: impl Into<String>) -> Self {
53        Mailer::Capture(Arc::new(Mutex::new(Vec::new())), from.into())
54    }
55
56    /// SMTP when `[smtp]` is present, otherwise capture for dev/test.
57    pub fn from_config(config: &Config) -> Result<Self, MailError> {
58        let mailer = match &config.smtp {
59            Some(smtp) => Mailer::Smtp {
60                transport: transport::build_transport(smtp)?,
61                default_from: config.mail_from.to_owned(),
62            },
63            None => Mailer::capture(config.mail_from.to_owned()),
64        };
65
66        Ok(mailer)
67    }
68
69    /// The default `From:` address for outgoing emails.
70    pub fn from(&self) -> &str {
71        match self {
72            Mailer::Smtp { default_from, .. } => default_from,
73            Mailer::Capture(_, from) => from,
74        }
75    }
76
77    /// Deliver an already-rendered email.
78    ///
79    /// Capture pushes synchronously; SMTP awaits delivery.
80    /// Callers that must not block (HTTP handlers) should spawn.
81    pub async fn send(&self, email: OutgoingEmail) -> Result<(), MailError> {
82        match self {
83            Mailer::Smtp { transport, .. } => {
84                let from_mbox: lettre::message::Mailbox = email.from.parse()?;
85                let to_mbox: lettre::message::Mailbox = email.to.parse()?;
86                let msg = lettre::Message::builder()
87                    .from(from_mbox)
88                    .to(to_mbox)
89                    .subject(&email.subject)
90                    .multipart(
91                        lettre::message::MultiPart::alternative()
92                            .singlepart(
93                                lettre::message::SinglePart::builder()
94                                    .header(lettre::message::header::ContentType::TEXT_PLAIN)
95                                    .body(email.text),
96                            )
97                            .singlepart(
98                                lettre::message::SinglePart::builder()
99                                    .header(lettre::message::header::ContentType::TEXT_HTML)
100                                    .body(email.html),
101                            ),
102                    )?;
103                transport.send(msg).await?;
104                tracing::info!(to = %email.to, subject = %email.subject, "email sent");
105                Ok(())
106            }
107            Mailer::Capture(store, _) => {
108                store.lock().unwrap().push(email);
109                Ok(())
110            }
111        }
112    }
113
114    /// All captured emails in insertion order.
115    pub fn all(&self) -> Vec<OutgoingEmail> {
116        match self {
117            Mailer::Capture(store, _) => {
118                let store = store.lock().unwrap();
119                store.clone()
120            }
121            Mailer::Smtp { .. } => vec![],
122        }
123    }
124
125    /// Get a single captured email by index.
126    pub fn get(&self, idx: usize) -> Option<OutgoingEmail> {
127        match self {
128            Mailer::Capture(store, _) => store.lock().unwrap().get(idx).cloned(),
129            Mailer::Smtp { .. } => None,
130        }
131    }
132
133    /// Clear the capture store.
134    pub fn clear(&self) {
135        match self {
136            Mailer::Capture(store, _) => store.lock().unwrap().clear(),
137            Mailer::Smtp { .. } => (),
138        }
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn capture_send_stores_email_synchronously() {
148        let mailer = Mailer::capture("test@example.com");
149
150        let email = OutgoingEmail {
151            from: "from@example.com".to_string(),
152            to: "to@example.com".to_string(),
153            subject: "Test".to_string(),
154            html: "<p>Hello</p>".to_string(),
155            text: "Hello".to_string(),
156        };
157
158        let rt = tokio::runtime::Runtime::new().unwrap();
159        rt.block_on(mailer.send(email))
160            .expect("send should succeed");
161
162        let stored = mailer.all();
163        assert_eq!(stored.len(), 1);
164        assert_eq!(stored[0].to, "to@example.com");
165        assert_eq!(stored[0].subject, "Test");
166        assert!(stored[0].html.contains("Hello"));
167    }
168
169    #[test]
170    fn capture_clear_empties_store() {
171        let mailer = Mailer::capture("test@example.com");
172
173        let rt = tokio::runtime::Runtime::new().unwrap();
174        rt.block_on(mailer.send(OutgoingEmail {
175            from: "from@example.com".to_string(),
176            to: "to@example.com".to_string(),
177            subject: "Test".to_string(),
178            html: "".to_string(),
179            text: "".to_string(),
180        }))
181        .expect("send");
182
183        assert_eq!(mailer.all().len(), 1);
184        mailer.clear();
185        assert_eq!(mailer.all().len(), 0);
186    }
187
188    #[test]
189    fn capture_get_returns_email_by_index() {
190        let mailer = Mailer::capture("test@example.com");
191
192        let rt = tokio::runtime::Runtime::new().unwrap();
193        rt.block_on(mailer.send(OutgoingEmail {
194            from: "a@x.com".to_string(),
195            to: "b@x.com".to_string(),
196            subject: "first".to_string(),
197            html: "".to_string(),
198            text: "".to_string(),
199        }))
200        .expect("send 1");
201        rt.block_on(mailer.send(OutgoingEmail {
202            from: "c@x.com".to_string(),
203            to: "d@x.com".to_string(),
204            subject: "second".to_string(),
205            html: "".to_string(),
206            text: "".to_string(),
207        }))
208        .expect("send 2");
209
210        assert_eq!(mailer.get(0).unwrap().subject, "first");
211        assert_eq!(mailer.get(1).unwrap().subject, "second");
212        assert!(mailer.get(2).is_none());
213    }
214}