Skip to main content

id_effect_mail/
lib.rs

1//! Outgoing mail for id_effect services: SMTP, the SendGrid v3 API, templates, and delivery through
2//! `id_effect_jobs`.
3//!
4//! [`Address`] is a validated `local@domain` mailbox address: no whitespace or control characters,
5//! a local part of at most [`Address::MAX_LOCAL_LEN`] bytes, a domain of non-empty dot-separated
6//! labels, and at most [`Address::MAX_LEN`] bytes in all (RFC 5321).
7//!
8//! ```
9//! use id_effect_mail::{Address, AddressError};
10//!
11//! let from = Address::parse("billing@ledger.example").unwrap();
12//! assert_eq!(from.to_string(), "billing@ledger.example");
13//! assert_eq!(Address::parse("billing"), Err(AddressError::MissingAt));
14//! ```
15//!
16//! A [`Message`] is built and checked by [`Message::builder`]: sender, `To` / `Cc` / `Bcc`,
17//! `Reply-To`, subject, text and HTML bodies, [`Attachment`]s, [`InlinePart`]s the HTML
18//! references as `cid:<content-id>`, and extra headers. It is sent through the [`Mailer`]
19//! capability ([`MailerService`], [`deliver`]), provided by one of three layers:
20//!
21//! - [`SmtpMailer::layer`]: pooled SMTP over lettre (implicit TLS, `STARTTLS` or plaintext).
22//! - [`SendGridMailer::layer`]: the SendGrid v3 API over the `HttpClient` capability.
23//! - [`TestMailbox::layer`]: records messages in memory, with `assert_sent_to`,
24//!   `assert_subject`, `assert_contains`.
25//!
26//! ```
27//! use id_effect::Exit;
28//! use id_effect_mail::{Address, MailerEnv, Message, TestMailbox, deliver};
29//!
30//! let message = Message::builder()
31//!   .from(Address::parse("billing@ledger.example").unwrap())
32//!   .to(Address::parse("carol@ledger.example").unwrap())
33//!   .subject("Your invoice")
34//!   .text("Your invoice is attached.")
35//!   .build()
36//!   .unwrap();
37//!
38//! let mailbox = TestMailbox::new();
39//! let program = deliver::<MailerEnv, _>(message).provide_layer(mailbox.layer());
40//! assert!(matches!(program.block_on(), Exit::Success(_)));
41//! mailbox.assert_sent_to("carol@ledger.example");
42//! mailbox.assert_subject("Your invoice");
43//! ```
44//!
45//! [`Templates`] renders a mail's subject, text and HTML bodies from minijinja templates with
46//! shared layouts and partials: HTML autoescaped, a missing variable an error
47//! ([`TemplateError`]), the context any `Serialize` value. With feature `preview`,
48//! `MailPreviews` serves registered previews at `/_mail/previews` (HTML, text and raw MIME),
49//! re-reading the templates from disk on every request in a debug build.
50//!
51//! ```
52//! use id_effect_mail::{Address, Templates};
53//!
54//! let templates = Templates::new()
55//!   .with_template("layout.txt", "{% block body %}{% endblock %}\n-- Ledger").unwrap()
56//!   .with_template("receipt.subject.txt", "Receipt {{ number }}").unwrap()
57//!   .with_template(
58//!     "receipt.txt",
59//!     r#"{% extends "layout.txt" %}{% block body %}Paid: {{ amount }}{% endblock %}"#,
60//!   )
61//!   .unwrap();
62//! let message = templates
63//!   .message("receipt", &serde_json::json!({ "number": 7, "amount": "12.00 EUR" }))
64//!   .unwrap()
65//!   .from(Address::parse("billing@ledger.example").unwrap())
66//!   .to(Address::parse("carol@ledger.example").unwrap())
67//!   .build()
68//!   .unwrap();
69//! assert_eq!(message.subject(), "Receipt 7");
70//! assert_eq!(message.text(), Some("Paid: 12.00 EUR\n-- Ledger"));
71//! ```
72//!
73//! Neither transport retries a send by itself; a refused send says whether a later attempt may
74//! succeed ([`MailError::is_transient`]). With feature `jobs`, `deliver_later` enqueues a message
75//! as a `DeliverMail` job of `id_effect_jobs` (`deliver_later_in` with the caller's SQL
76//! transaction, so it is sent only if that commits), and `register_mail_jobs` adds the handler
77//! that sends it through the [`Mailer`]: a transient failure is retried with backoff, any other
78//! makes the job `dead` with the error recorded.
79//!
80//! With feature `auth`, `AccountMails` implements `id_effect_auth`'s `AccountNotifier`: the
81//! verification and password reset mails, rendered from templates and sent directly through the
82//! [`Mailer`] with a short retry. They never go through `deliver_later`, whose job payload would
83//! keep a usable token in the jobs table (see the `auth` module).
84//!
85//! Tier `platform` (ADR 0010 Amendment 6): the Ledger reference app under
86//! `examples/reference/` depends on it.
87
88#![forbid(unsafe_code)]
89#![deny(missing_docs)]
90
91use std::fmt;
92
93#[cfg(feature = "auth")]
94pub mod auth;
95#[cfg(feature = "jobs")]
96mod later;
97mod mailer;
98mod message;
99#[cfg(feature = "preview")]
100mod preview;
101mod sendgrid;
102mod smtp;
103mod template;
104mod testing;
105
106#[cfg(feature = "auth")]
107pub use auth::AccountMails;
108#[cfg(feature = "jobs")]
109pub use later::{DeliverMail, deliver_later, deliver_later_in, register_mail_jobs};
110pub use mailer::{
111  MailError, Mailer, MailerEnv, MailerService, Sent, deliver, mailer_env, provide_mailer,
112};
113pub use message::{Attachment, InlinePart, Mailbox, Message, MessageBuilder};
114#[cfg(feature = "preview")]
115pub use preview::{MailPreviews, PREVIEWS_PATH};
116pub use sendgrid::{SendGridConfig, SendGridMailer};
117pub use smtp::{SmtpConfig, SmtpMailer, SmtpSecurity};
118pub use template::{RenderedMail, TemplateError, Templates};
119pub use testing::TestMailbox;
120
121/// A validated `local@domain` mailbox address.
122#[derive(Clone, Debug, PartialEq, Eq, Hash)]
123pub struct Address {
124  addr: String,
125  at: usize,
126}
127
128impl Address {
129  /// Longest address, in bytes (RFC 5321 path limit minus the angle brackets).
130  pub const MAX_LEN: usize = 254;
131  /// Longest local part, in bytes (RFC 5321).
132  pub const MAX_LOCAL_LEN: usize = 64;
133
134  /// Validates `addr` as a mailbox address.
135  pub fn parse(addr: impl Into<String>) -> Result<Self, AddressError> {
136    let addr = addr.into();
137    if addr.chars().any(|c| c.is_whitespace() || c.is_control()) {
138      return Err(AddressError::Whitespace);
139    }
140    let (local, domain) = addr.split_once('@').ok_or(AddressError::MissingAt)?;
141    if local.is_empty() {
142      return Err(AddressError::EmptyLocal);
143    }
144    if local.len() > Self::MAX_LOCAL_LEN {
145      return Err(AddressError::LocalTooLong);
146    }
147    if domain.contains('@') || domain.split('.').any(str::is_empty) {
148      return Err(AddressError::InvalidDomain);
149    }
150    if addr.len() > Self::MAX_LEN {
151      return Err(AddressError::TooLong);
152    }
153    let at = local.len();
154    Ok(Address { addr, at })
155  }
156
157  /// The part before the `@`.
158  pub fn local(&self) -> &str {
159    &self.addr[..self.at]
160  }
161
162  /// The part after the `@`.
163  pub fn domain(&self) -> &str {
164    &self.addr[self.at + 1..]
165  }
166
167  /// The whole address.
168  pub fn as_str(&self) -> &str {
169    &self.addr
170  }
171}
172
173impl fmt::Display for Address {
174  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175    f.write_str(&self.addr)
176  }
177}
178
179/// Why a string is not a valid [`Address`].
180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
181pub enum AddressError {
182  /// It contains whitespace or a control character.
183  Whitespace,
184  /// It has no `@`.
185  MissingAt,
186  /// Nothing comes before the `@`.
187  EmptyLocal,
188  /// The local part is longer than [`Address::MAX_LOCAL_LEN`] bytes.
189  LocalTooLong,
190  /// The domain is empty, has an empty label (`a..b`, a leading or trailing dot) or another `@`.
191  InvalidDomain,
192  /// The address is longer than [`Address::MAX_LEN`] bytes.
193  TooLong,
194}
195
196impl fmt::Display for AddressError {
197  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198    f.write_str(match self {
199      AddressError::Whitespace => "mail address contains whitespace or a control character",
200      AddressError::MissingAt => "mail address has no `@`",
201      AddressError::EmptyLocal => "mail address has nothing before the `@`",
202      AddressError::LocalTooLong => "mail address local part is longer than 64 bytes",
203      AddressError::InvalidDomain => "mail address domain is not a dot-separated host name",
204      AddressError::TooLong => "mail address is longer than 254 bytes",
205    })
206  }
207}
208
209impl std::error::Error for AddressError {}
210
211/// Runs the book chapter on mail as a doctest (its blocks need features `preview` and `jobs`).
212#[cfg(all(doctest, feature = "preview", feature = "jobs"))]
213#[doc = include_str!("../../id_effect/book/src/part6/ch31-03-mail.md")]
214struct BookMailDoctests;