capy-mail 0.10.0

Conventional SMTP mail, typed templates, and mail notifications for Capy.
Documentation
//! Transactional application mail. Queued sends are at-least-once, not exactly-once.
//! Secrets and attachment contents belong in application-owned protected storage,
//! never in generic plaintext job payloads. SMTP provider acceptance is not inbox delivery.
mod capture;
mod error;
pub use capture::{CapturedMail, DevelopmentInbox};
mod message;
pub mod notifications;
#[cfg(feature = "jobs")]
mod queued;
mod transport;
pub use askama;
use capy_core::{AppConfig, AppError};
pub use capy_core::{MailSettings, SmtpSettings};
pub use error::MailError;
/// Native SMTP/MIME escape hatch for custom transports; not needed for conventional mail.
pub use lettre;
use lettre::{transport::smtp::authentication::Credentials, AsyncSmtpTransport, Tokio1Executor};
pub use message::{Attachment, Envelope, Mail, Mailable, Mailbox, QueueableMail};
#[cfg(feature = "jobs")]
pub use queued::{register_jobs, validate_jobs};
use std::{
    sync::Arc,
    time::{Duration, Instant},
};
pub use transport::{CaptureTransport, DeliveryReceipt, LogTransport, MailTransport, PreparedMail};

/// Mail-specific safe result.
pub type MailResult<T> = Result<T, MailError>;

/// A payload-free lifecycle observation for application telemetry.
#[derive(Clone, Debug)]
pub struct MailObservation {
    /// `mail.sending`, `mail.sent`, `mail.failed`, or `mail.queued`.
    pub event: &'static str,
    /// Explicit safe mailable/notification name.
    pub message_type: String,
    /// Static transport label.
    pub transport: &'static str,
    /// Elapsed operation time.
    pub duration: Duration,
    /// Associated queue UUID, if this operation is queued.
    pub queue_job_id: Option<String>,
    /// Safe error classification.
    pub error_category: Option<&'static str>,
}
/// Nonblocking application metrics hook. Contains no subject/body/recipient fields.
pub trait MailObserver: Send + Sync + 'static {
    /// Record a transition without blocking or performing network operations.
    fn observe(&self, observation: &MailObservation);
}
/// Cloneable mail service. Clones share transport policy and application observer hooks.
#[derive(Clone)]
pub struct Mailer {
    pub(crate) settings: MailSettings,
    from: Mailbox,
    application_url: Option<url::Url>,
    transport: Arc<dyn MailTransport>,
    observer: Option<Arc<dyn MailObserver>>,
}
impl std::fmt::Debug for Mailer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Mailer([REDACTED])")
    }
}
impl Mailer {
    /// Offline validation, including typed addresses and production safety.
    pub fn validate(config: &AppConfig) -> capy_core::Result<()> {
        config.mail.validate()?;
        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()))?;
        application_url(config)?;
        if config.app.environment == "production" {
            if config.mail.driver != "smtp" {
                return Err(AppError::Configuration("Production mail requires MAIL_DRIVER=smtp; log/capture transports do not deliver mail.".into()));
            }
            if config.mail.smtp.encryption == "none" {
                return Err(AppError::Configuration("Production SMTP requires MAIL_SMTP_ENCRYPTION=starttls or tls; plaintext/downgrade is forbidden.".into()));
            }
        }
        Ok(())
    }
    /// Build SMTP connection policy or a metadata-only development sink. No network call occurs.
    pub fn from_config(config: &AppConfig) -> capy_core::Result<Self> {
        Self::validate(config)?;
        if config.mail.driver == "log" {
            return Self::with_transport(config, LogTransport);
        }
        if config.mail.driver == "capture" {
            return Self::with_transport(
                config,
                DevelopmentInbox::new(&config.mail.capture_directory),
            );
        }
        let smtp = &config.mail.smtp;
        let builder = match smtp.encryption.as_str() {
            "starttls" => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&smtp.host)
                .map_err(|_| {
                    AppError::Configuration(
                        "Cannot configure SMTP STARTTLS; check MAIL_SMTP_HOST.".into(),
                    )
                })?,
            "tls" => AsyncSmtpTransport::<Tokio1Executor>::relay(&smtp.host).map_err(|_| {
                AppError::Configuration("Cannot configure SMTP TLS; check MAIL_SMTP_HOST.".into())
            })?,
            _ => AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&smtp.host),
        };
        let mut builder = builder
            .port(smtp.port)
            .timeout(Some(Duration::from_secs(config.mail.timeout_seconds)));
        if !smtp.username.expose().is_empty() {
            builder = builder.credentials(Credentials::new(
                smtp.username.expose().into(),
                smtp.password.expose().into(),
            ));
        }
        Self::with_transport(config, transport::SmtpTransport(builder))
    }
    /// Create a real-rendering in-memory mailer and its assertion handle. No worker
    /// setup is required for direct mail; attach it with `App::with_mail`.
    /// Production rejects this development-only transport.
    pub fn capture(config: &AppConfig) -> capy_core::Result<(Self, CaptureTransport)> {
        let capture = CaptureTransport::new();
        Ok((Self::with_transport(config, capture.clone())?, capture))
    }
    /// Install an application/test transport. Production rejects `development_only` adapters.
    pub fn with_transport(
        config: &AppConfig,
        transport: impl MailTransport,
    ) -> capy_core::Result<Self> {
        config.mail.validate()?;
        let application_url = application_url(config)?;
        if config.app.environment == "production" && transport.development_only() {
            return Err(AppError::Configuration(
                "Production mail cannot use a development/capture transport.".into(),
            ));
        }
        validate_name(transport.name()).map_err(|_| {
            AppError::Configuration("Custom mail transports require a safe static name.".into())
        })?;
        let from = Mailbox::new(&config.mail.from_address, config.mail.from_name.clone())
            .map_err(|_| AppError::Configuration("Invalid configured mail sender.".into()))?;
        Ok(Self {
            settings: config.mail.clone(),
            from,
            application_url,
            transport: Arc::new(transport),
            observer: None,
        })
    }
    /// Whether this transport is a development-only sink. Delivery adapters can
    /// propagate this flag to authentication production validation.
    pub fn development_only(&self) -> bool {
        self.transport.development_only()
    }
    /// Check a previously built service before attaching it to an application.
    pub fn validate_environment(&self, production: bool) -> capy_core::Result<()> {
        if production
            && (self.transport.development_only()
                || self
                    .application_url
                    .as_ref()
                    .is_none_or(|u| u.scheme() != "https")
                || (self.transport.name() == "smtp" && self.settings.smtp.encryption == "none"))
        {
            return Err(AppError::Configuration("Production mail requires a delivering transport, encrypted SMTP and an explicit HTTPS APP_URL.".into()));
        }
        Ok(())
    }
    /// Install a safe nonblocking telemetry callback.
    pub fn observe(mut self, observer: impl MailObserver) -> Self {
        self.observer = Some(Arc::new(observer));
        self
    }
    /// Generate an absolute URL from configured APP_URL and an application-owned path.
    /// Request headers are never consulted. Add sensitive reset credentials as fragments.
    pub fn absolute_url(&self, path: &str) -> MailResult<url::Url> {
        if !path.starts_with('/')
            || path.starts_with("//")
            || path.contains(['\\', '#', '?'])
            || path.chars().any(char::is_control)
        {
            return Err(MailError::Configuration);
        }
        let base = self
            .application_url
            .as_ref()
            .ok_or(MailError::Configuration)?;
        let url = base.join(path).map_err(|_| MailError::Configuration)?;
        if url.origin() != base.origin() {
            return Err(MailError::Configuration);
        }
        Ok(url)
    }
    /// Render and send once, with no automatic retries.
    pub async fn send<M: Mailable>(&self, envelope: Envelope<M>) -> MailResult<DeliveryReceipt> {
        let mail = envelope.content.render().map(|m| m.to(envelope.recipient));
        self.send_rendered(M::NAME, mail, None, None).await
    }
    /// Low-level typed message delivery, using an explicit safe diagnostic name.
    pub async fn send_mail(&self, message_type: &str, mail: Mail) -> MailResult<DeliveryReceipt> {
        self.send_rendered(message_type, Ok(mail), None, None).await
    }
    pub(crate) async fn send_rendered(
        &self,
        message_type: &str,
        mail: MailResult<Mail>,
        id: Option<String>,
        job: Option<&str>,
    ) -> MailResult<DeliveryReceipt> {
        validate_name(message_type)?;
        let start = Instant::now();
        self.emit("mail.sending", message_type, start.elapsed(), job, None);
        let result = async {
            let prepared = self.prepare(message_type, mail?, id)?;
            tokio::time::timeout(
                Duration::from_secs(self.settings.timeout_seconds),
                self.transport.send(prepared),
            )
            .await
            .map_err(|_| MailError::Timeout)?
        }
        .await;
        self.emit(
            if result.is_ok() {
                "mail.sent"
            } else {
                "mail.failed"
            },
            message_type,
            start.elapsed(),
            job,
            result.as_ref().err().copied(),
        );
        result
    }
    pub(crate) fn prepare(
        &self,
        message_type: &str,
        mail: Mail,
        id: Option<String>,
    ) -> MailResult<PreparedMail> {
        validate_name(message_type)?;
        let message_id = id.unwrap_or_else(|| {
            format!("<{}@{}>", uuid::Uuid::new_v4(), self.from.0.email.domain())
        });
        // IDs supplied by queue payloads must never inject arbitrary header text.
        message::header_text(&message_id)?;
        if !message_id.starts_with('<')
            || !message_id.ends_with('>')
            || message_id.len() > 200
            || !message_id.contains('@')
        {
            return Err(MailError::Header);
        }
        let recipients = mail
            .to
            .iter()
            .chain(&mail.cc)
            .chain(&mail.bcc)
            .cloned()
            .collect();
        let subject = mail.subject.clone();
        let content = capture::CaptureContent::new(&mail, &self.from);
        let message = mail.build(&self.from, self.settings.max_message_bytes, &message_id)?;
        Ok(PreparedMail {
            message,
            content,
            message_type: message_type.into(),
            message_id,
            subject,
            recipients,
        })
    }
    pub(crate) fn emit(
        &self,
        event: &'static str,
        name: &str,
        duration: Duration,
        job: Option<&str>,
        error: Option<MailError>,
    ) {
        let observation = MailObservation {
            event,
            message_type: name.into(),
            transport: self.transport.name(),
            duration,
            queue_job_id: job.map(str::to_owned),
            error_category: error.map(MailError::category),
        };
        tracing::info!(
            event,
            message_type = name,
            transport = observation.transport,
            duration_ms = duration.as_millis() as u64,
            queue_job_id = job,
            error_category = observation.error_category,
            "mail lifecycle"
        );
        if let Some(observer) = &self.observer {
            if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                observer.observe(&observation)
            }))
            .is_err()
            {
                tracing::warn!(error_category = "observer_panic", "mail observer panicked");
            }
        }
    }
}
fn application_url(config: &AppConfig) -> capy_core::Result<Option<url::Url>> {
    let invalid = || {
        AppError::Configuration("Mail requires a valid APP_URL (HTTPS in production), without credentials, query or fragment.".into())
    };
    let Some(value) = &config.app.url else {
        return if config.app.environment == "production" {
            Err(invalid())
        } else {
            Ok(None)
        };
    };
    let url = url::Url::parse(value).map_err(|_| invalid())?;
    if !matches!(url.scheme(), "http" | "https")
        || url.host_str().is_none()
        || !url.username().is_empty()
        || url.password().is_some()
        || url.query().is_some()
        || url.fragment().is_some()
        || (config.app.environment == "production" && url.scheme() != "https")
    {
        return Err(invalid());
    }
    Ok(Some(url))
}
pub(crate) fn validate_name(value: &str) -> MailResult<()> {
    if value.is_empty()
        || value.len() > 128
        || !value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))
    {
        Err(MailError::Configuration)
    } else {
        Ok(())
    }
}
/// HTTP extractor for the shared mail service installed by `App::mail`/`with_mail`.
#[derive(Clone, Debug)]
pub struct MailContext(pub Mailer);
impl<S: Send + Sync> axum::extract::FromRequestParts<S> for MailContext {
    type Rejection = AppError;
    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _: &S,
    ) -> capy_core::Result<Self> {
        parts
            .extensions
            .get::<Mailer>()
            .cloned()
            .map(Self)
            .ok_or_else(|| {
                AppError::Configuration("Install App::mail before using MailContext.".into())
            })
    }
}

#[cfg(all(test, feature = "jobs"))]
mod benchmarks;