1mod capture;
5mod error;
6pub use capture::{CapturedMail, DevelopmentInbox};
7mod message;
8pub mod notifications;
9#[cfg(feature = "jobs")]
10mod queued;
11mod transport;
12pub use askama;
13use capy_core::{AppConfig, AppError};
14pub use capy_core::{MailSettings, SmtpSettings};
15pub use error::MailError;
16pub use lettre;
18use lettre::{transport::smtp::authentication::Credentials, AsyncSmtpTransport, Tokio1Executor};
19pub use message::{Attachment, Envelope, Mail, Mailable, Mailbox, QueueableMail};
20#[cfg(feature = "jobs")]
21pub use queued::{register_jobs, validate_jobs};
22use std::{
23 sync::Arc,
24 time::{Duration, Instant},
25};
26pub use transport::{CaptureTransport, DeliveryReceipt, LogTransport, MailTransport, PreparedMail};
27
28pub type MailResult<T> = Result<T, MailError>;
30
31#[derive(Clone, Debug)]
33pub struct MailObservation {
34 pub event: &'static str,
36 pub message_type: String,
38 pub transport: &'static str,
40 pub duration: Duration,
42 pub queue_job_id: Option<String>,
44 pub error_category: Option<&'static str>,
46}
47pub trait MailObserver: Send + Sync + 'static {
49 fn observe(&self, observation: &MailObservation);
51}
52#[derive(Clone)]
54pub struct Mailer {
55 pub(crate) settings: MailSettings,
56 from: Mailbox,
57 application_url: Option<url::Url>,
58 transport: Arc<dyn MailTransport>,
59 observer: Option<Arc<dyn MailObserver>>,
60}
61impl std::fmt::Debug for Mailer {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 f.write_str("Mailer([REDACTED])")
64 }
65}
66impl Mailer {
67 pub fn validate(config: &AppConfig) -> capy_core::Result<()> {
69 config.mail.validate()?;
70 Mailbox::new(&config.mail.from_address, config.mail.from_name.clone()).map_err(|_| AppError::Configuration("MAIL_FROM_ADDRESS/MAIL_FROM_NAME must form a valid mailbox without control characters.".into()))?;
71 application_url(config)?;
72 if config.app.environment == "production" {
73 if config.mail.driver != "smtp" {
74 return Err(AppError::Configuration("Production mail requires MAIL_DRIVER=smtp; log/capture transports do not deliver mail.".into()));
75 }
76 if config.mail.smtp.encryption == "none" {
77 return Err(AppError::Configuration("Production SMTP requires MAIL_SMTP_ENCRYPTION=starttls or tls; plaintext/downgrade is forbidden.".into()));
78 }
79 }
80 Ok(())
81 }
82 pub fn from_config(config: &AppConfig) -> capy_core::Result<Self> {
84 Self::validate(config)?;
85 if config.mail.driver == "log" {
86 return Self::with_transport(config, LogTransport);
87 }
88 if config.mail.driver == "capture" {
89 return Self::with_transport(
90 config,
91 DevelopmentInbox::new(&config.mail.capture_directory),
92 );
93 }
94 let smtp = &config.mail.smtp;
95 let builder = match smtp.encryption.as_str() {
96 "starttls" => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&smtp.host)
97 .map_err(|_| {
98 AppError::Configuration(
99 "Cannot configure SMTP STARTTLS; check MAIL_SMTP_HOST.".into(),
100 )
101 })?,
102 "tls" => AsyncSmtpTransport::<Tokio1Executor>::relay(&smtp.host).map_err(|_| {
103 AppError::Configuration("Cannot configure SMTP TLS; check MAIL_SMTP_HOST.".into())
104 })?,
105 _ => AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&smtp.host),
106 };
107 let mut builder = builder
108 .port(smtp.port)
109 .timeout(Some(Duration::from_secs(config.mail.timeout_seconds)));
110 if !smtp.username.expose().is_empty() {
111 builder = builder.credentials(Credentials::new(
112 smtp.username.expose().into(),
113 smtp.password.expose().into(),
114 ));
115 }
116 Self::with_transport(config, transport::SmtpTransport(builder))
117 }
118 pub fn capture(config: &AppConfig) -> capy_core::Result<(Self, CaptureTransport)> {
122 let capture = CaptureTransport::new();
123 Ok((Self::with_transport(config, capture.clone())?, capture))
124 }
125 pub fn with_transport(
127 config: &AppConfig,
128 transport: impl MailTransport,
129 ) -> capy_core::Result<Self> {
130 config.mail.validate()?;
131 let application_url = application_url(config)?;
132 if config.app.environment == "production" && transport.development_only() {
133 return Err(AppError::Configuration(
134 "Production mail cannot use a development/capture transport.".into(),
135 ));
136 }
137 validate_name(transport.name()).map_err(|_| {
138 AppError::Configuration("Custom mail transports require a safe static name.".into())
139 })?;
140 let from = Mailbox::new(&config.mail.from_address, config.mail.from_name.clone())
141 .map_err(|_| AppError::Configuration("Invalid configured mail sender.".into()))?;
142 Ok(Self {
143 settings: config.mail.clone(),
144 from,
145 application_url,
146 transport: Arc::new(transport),
147 observer: None,
148 })
149 }
150 pub fn development_only(&self) -> bool {
153 self.transport.development_only()
154 }
155 pub fn validate_environment(&self, production: bool) -> capy_core::Result<()> {
157 if production
158 && (self.transport.development_only()
159 || self
160 .application_url
161 .as_ref()
162 .is_none_or(|u| u.scheme() != "https")
163 || (self.transport.name() == "smtp" && self.settings.smtp.encryption == "none"))
164 {
165 return Err(AppError::Configuration("Production mail requires a delivering transport, encrypted SMTP and an explicit HTTPS APP_URL.".into()));
166 }
167 Ok(())
168 }
169 pub fn observe(mut self, observer: impl MailObserver) -> Self {
171 self.observer = Some(Arc::new(observer));
172 self
173 }
174 pub fn absolute_url(&self, path: &str) -> MailResult<url::Url> {
177 if !path.starts_with('/')
178 || path.starts_with("//")
179 || path.contains(['\\', '#', '?'])
180 || path.chars().any(char::is_control)
181 {
182 return Err(MailError::Configuration);
183 }
184 let base = self
185 .application_url
186 .as_ref()
187 .ok_or(MailError::Configuration)?;
188 let url = base.join(path).map_err(|_| MailError::Configuration)?;
189 if url.origin() != base.origin() {
190 return Err(MailError::Configuration);
191 }
192 Ok(url)
193 }
194 pub async fn send<M: Mailable>(&self, envelope: Envelope<M>) -> MailResult<DeliveryReceipt> {
196 let mail = envelope.content.render().map(|m| m.to(envelope.recipient));
197 self.send_rendered(M::NAME, mail, None, None).await
198 }
199 pub async fn send_mail(&self, message_type: &str, mail: Mail) -> MailResult<DeliveryReceipt> {
201 self.send_rendered(message_type, Ok(mail), None, None).await
202 }
203 pub(crate) async fn send_rendered(
204 &self,
205 message_type: &str,
206 mail: MailResult<Mail>,
207 id: Option<String>,
208 job: Option<&str>,
209 ) -> MailResult<DeliveryReceipt> {
210 validate_name(message_type)?;
211 let start = Instant::now();
212 self.emit("mail.sending", message_type, start.elapsed(), job, None);
213 let result = async {
214 let prepared = self.prepare(message_type, mail?, id)?;
215 tokio::time::timeout(
216 Duration::from_secs(self.settings.timeout_seconds),
217 self.transport.send(prepared),
218 )
219 .await
220 .map_err(|_| MailError::Timeout)?
221 }
222 .await;
223 self.emit(
224 if result.is_ok() {
225 "mail.sent"
226 } else {
227 "mail.failed"
228 },
229 message_type,
230 start.elapsed(),
231 job,
232 result.as_ref().err().copied(),
233 );
234 result
235 }
236 pub(crate) fn prepare(
237 &self,
238 message_type: &str,
239 mail: Mail,
240 id: Option<String>,
241 ) -> MailResult<PreparedMail> {
242 validate_name(message_type)?;
243 let message_id = id.unwrap_or_else(|| {
244 format!("<{}@{}>", uuid::Uuid::new_v4(), self.from.0.email.domain())
245 });
246 message::header_text(&message_id)?;
248 if !message_id.starts_with('<')
249 || !message_id.ends_with('>')
250 || message_id.len() > 200
251 || !message_id.contains('@')
252 {
253 return Err(MailError::Header);
254 }
255 let recipients = mail
256 .to
257 .iter()
258 .chain(&mail.cc)
259 .chain(&mail.bcc)
260 .cloned()
261 .collect();
262 let subject = mail.subject.clone();
263 let content = capture::CaptureContent::new(&mail, &self.from);
264 let message = mail.build(&self.from, self.settings.max_message_bytes, &message_id)?;
265 Ok(PreparedMail {
266 message,
267 content,
268 message_type: message_type.into(),
269 message_id,
270 subject,
271 recipients,
272 })
273 }
274 pub(crate) fn emit(
275 &self,
276 event: &'static str,
277 name: &str,
278 duration: Duration,
279 job: Option<&str>,
280 error: Option<MailError>,
281 ) {
282 let observation = MailObservation {
283 event,
284 message_type: name.into(),
285 transport: self.transport.name(),
286 duration,
287 queue_job_id: job.map(str::to_owned),
288 error_category: error.map(MailError::category),
289 };
290 tracing::info!(
291 event,
292 message_type = name,
293 transport = observation.transport,
294 duration_ms = duration.as_millis() as u64,
295 queue_job_id = job,
296 error_category = observation.error_category,
297 "mail lifecycle"
298 );
299 if let Some(observer) = &self.observer {
300 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
301 observer.observe(&observation)
302 }))
303 .is_err()
304 {
305 tracing::warn!(error_category = "observer_panic", "mail observer panicked");
306 }
307 }
308 }
309}
310fn application_url(config: &AppConfig) -> capy_core::Result<Option<url::Url>> {
311 let invalid = || {
312 AppError::Configuration("Mail requires a valid APP_URL (HTTPS in production), without credentials, query or fragment.".into())
313 };
314 let Some(value) = &config.app.url else {
315 return if config.app.environment == "production" {
316 Err(invalid())
317 } else {
318 Ok(None)
319 };
320 };
321 let url = url::Url::parse(value).map_err(|_| invalid())?;
322 if !matches!(url.scheme(), "http" | "https")
323 || url.host_str().is_none()
324 || !url.username().is_empty()
325 || url.password().is_some()
326 || url.query().is_some()
327 || url.fragment().is_some()
328 || (config.app.environment == "production" && url.scheme() != "https")
329 {
330 return Err(invalid());
331 }
332 Ok(Some(url))
333}
334pub(crate) fn validate_name(value: &str) -> MailResult<()> {
335 if value.is_empty()
336 || value.len() > 128
337 || !value
338 .bytes()
339 .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))
340 {
341 Err(MailError::Configuration)
342 } else {
343 Ok(())
344 }
345}
346#[derive(Clone, Debug)]
348pub struct MailContext(pub Mailer);
349impl<S: Send + Sync> axum::extract::FromRequestParts<S> for MailContext {
350 type Rejection = AppError;
351 async fn from_request_parts(
352 parts: &mut axum::http::request::Parts,
353 _: &S,
354 ) -> capy_core::Result<Self> {
355 parts
356 .extensions
357 .get::<Mailer>()
358 .cloned()
359 .map(Self)
360 .ok_or_else(|| {
361 AppError::Configuration("Install App::mail before using MailContext.".into())
362 })
363 }
364}
365
366#[cfg(all(test, feature = "jobs"))]
367mod benchmarks;