1use 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
37const OUTBOX: usize = 50;
39
40#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
57#[non_exhaustive]
58pub struct Mail {
59 pub to: Vec<String>,
61 pub subject: String,
63 pub text: String,
65 #[serde(default)]
67 pub html: Option<String>,
68 #[serde(default)]
70 pub cc: Vec<String>,
71 #[serde(default)]
73 pub bcc: Vec<String>,
74 #[serde(default)]
76 pub reply_to: Option<String>,
77 #[serde(default)]
79 pub from: Option<String>,
80 #[serde(default)]
82 pub attachments: Vec<Attachment>,
83}
84
85const MAIL_BUTTON_COLORS: &str = "background:#1c1917;color:#ffffff;";
88const MAIL_PANEL_STRIPE: &str = "border-left:4px solid #1c1917;";
89
90#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
92#[non_exhaustive]
93pub struct Attachment {
94 pub filename: String,
96 pub content_type: String,
98 #[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 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 pub fn html(mut self, html: impl Into<String>) -> Self {
136 self.html = Some(html.into());
137 self
138 }
139
140 pub fn also_to(mut self, address: impl Into<String>) -> Self {
142 self.to.push(address.into());
143 self
144 }
145
146 pub fn cc(mut self, address: impl Into<String>) -> Self {
148 self.cc.push(address.into());
149 self
150 }
151
152 pub fn bcc(mut self, address: impl Into<String>) -> Self {
154 self.bcc.push(address.into());
155 self
156 }
157
158 pub fn reply_to(mut self, address: impl Into<String>) -> Self {
160 self.reply_to = Some(address.into());
161 self
162 }
163
164 pub fn from(mut self, address: impl Into<String>) -> Self {
166 self.from = Some(address.into());
167 self
168 }
169
170 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 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 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 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 pub enum MailDriver ("MAIL_MAILER") {
261 Smtp = "smtp",
263 Log = "log",
265 Memory = "memory",
267 }
268}
269
270setting_enum! {
271 pub enum MailEncryption ("MAIL_ENCRYPTION") {
273 Tls = "tls",
275 StartTls = "starttls",
277 None = "none",
279 }
280}
281
282#[derive(Clone)]
284#[non_exhaustive]
285pub struct MailConfig {
286 pub mailer: MailDriver,
288 pub host: String,
290 pub port: Option<u16>,
292 pub username: Option<String>,
294 pub password: Option<String>,
296 pub encryption: MailEncryption,
298 pub from_address: String,
300 pub from_name: Option<String>,
302 pub timeout: std::time::Duration,
305 pub failover: Vec<String>,
309}
310
311impl std::fmt::Debug for MailConfig {
312 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 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#[derive(Clone)]
417pub struct Mailer {
418 driver: Driver,
419 failover: Vec<(String, Driver)>,
421 outbox: Arc<Mutex<(u64, VecDeque<Sent>)>>,
422 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 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 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 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 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
516async 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 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#[derive(Serialize, Deserialize)]
644pub(crate) struct SendMail {
645 #[serde(flatten)]
647 mail: Mail,
648 #[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#[derive(Serialize, Deserialize)]
669pub(crate) struct SendMailVia {
670 pub mailer: String,
671 pub mail: Mail,
672 #[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 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 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 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 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 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 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
774pub(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 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(" ", " ")
827 .replace("<", "<")
828 .replace(">", ">")
829 .replace(""", "\"")
830 .replace("'", "'")
831 .replace("'", "'")
832 .replace("/", "/")
833 .replace("&", "&");
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
854pub(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('&', "&")
863 .replace('<', "<")
864 .replace('>', ">")
865 .replace('"', """)
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\">← 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 let queued: Mail = serde_json::from_str(&serde_json::to_string(&mail).unwrap()).unwrap();
974 assert_eq!(queued, mail);
975 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 & welcome</h1><p>Click <a href="https://x.id/a?b=1&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 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 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 #[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 #[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}