capy-mail 0.10.0

Conventional SMTP mail, typed templates, and mail notifications for Capy.
Documentation
use crate::{CapturedMail, MailError, MailResult, Mailbox};
use lettre::{AsyncTransport, Tokio1Executor};
use std::{
    future::Future,
    pin::Pin,
    sync::{Arc, Mutex},
};

/// MIME message and explicit metadata for a transport. Debug never includes contents.
pub struct PreparedMail {
    pub(crate) message: lettre::Message,
    pub(crate) message_type: String,
    pub(crate) message_id: String,
    pub(crate) subject: String,
    pub(crate) recipients: Vec<Mailbox>,
    pub(crate) content: crate::capture::CaptureContent,
}
impl PreparedMail {
    /// Native escape hatch for application transports. Contains private message data.
    pub fn message(&self) -> &lettre::Message {
        &self.message
    }
    /// Safe application type name.
    pub fn message_type(&self) -> &str {
        &self.message_type
    }
    /// Conventional Message-ID; retained across built-in queue retries.
    pub fn message_id(&self) -> &str {
        &self.message_id
    }
}
impl std::fmt::Debug for PreparedMail {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("PreparedMail([REDACTED])")
    }
}
/// Provider acceptance, not a guarantee of inbox delivery or exactly-once effects.
#[derive(Clone)]
pub struct DeliveryReceipt {
    /// Conventional Message-ID; an operational identifier, not a secret.
    pub message_id: String,
    /// Optional application transport identifier. Capy's SMTP transport leaves this unset.
    pub provider_id: Option<String>,
}
impl std::fmt::Debug for DeliveryReceipt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("DeliveryReceipt([REDACTED])")
    }
}
/// A small application-owned transport, independent of SMTP/Jobs implementation details.
pub trait MailTransport: Send + Sync + 'static {
    /// Safe static transport label; never return credentials or host URLs here.
    fn name(&self) -> &'static str;
    /// Reject non-delivering transports in production.
    fn development_only(&self) -> bool {
        false
    }
    /// Submit a fully rendered and validated MIME message. Do not log its content.
    fn send(
        &self,
        mail: PreparedMail,
    ) -> Pin<Box<dyn Future<Output = MailResult<DeliveryReceipt>> + Send + '_>>;
}
pub(crate) struct SmtpTransport(pub lettre::transport::smtp::AsyncSmtpTransportBuilder);
impl MailTransport for SmtpTransport {
    fn name(&self) -> &'static str {
        "smtp"
    }
    fn send(
        &self,
        mail: PreparedMail,
    ) -> Pin<Box<dyn Future<Output = MailResult<DeliveryReceipt>> + Send + '_>> {
        Box::pin(async move {
            // Own the transport for this send. Even if an application's feature
            // unification enables Lettre pooling, a cancelled send cannot return an
            // uncertain SMTP session to a transport used by a later message.
            let transport = self.0.clone().build::<Tokio1Executor>();
            transport.send(mail.message).await.map_err(classify)?;
            Ok(DeliveryReceipt {
                message_id: mail.message_id,
                provider_id: None,
            })
        })
    }
}
fn classify(error: lettre::transport::smtp::Error) -> MailError {
    if error.is_timeout() {
        MailError::Timeout
    } else if error.is_tls() {
        MailError::Tls
    } else if error
        .status()
        .is_some_and(|s| matches!(s.to_string().as_str(), "530" | "534" | "535" | "538"))
    {
        MailError::Authentication
    } else if error.is_transient() {
        MailError::Temporary
    } else if error.is_permanent() {
        MailError::Permanent
    } else if error.is_client() {
        MailError::Configuration
    } else {
        MailError::Connection
    }
}
/// Development sink: lifecycle metadata only, never body, subject or recipients.
pub struct LogTransport;
impl MailTransport for LogTransport {
    fn name(&self) -> &'static str {
        "log"
    }
    fn development_only(&self) -> bool {
        true
    }
    fn send(
        &self,
        mail: PreparedMail,
    ) -> Pin<Box<dyn Future<Output = MailResult<DeliveryReceipt>> + Send + '_>> {
        Box::pin(async move {
            Ok(DeliveryReceipt {
                message_id: mail.message_id,
                provider_id: None,
            })
        })
    }
}

/// Bounded in-memory test transport; runs real rendering, parsing and MIME construction.
#[derive(Clone, Default)]
pub struct CaptureTransport(Arc<Mutex<Vec<CapturedMail>>>);
impl CaptureTransport {
    /// Create an empty capture with a maximum of 100 messages and 64 MiB encoded content.
    pub fn new() -> Self {
        Self::default()
    }
    /// Assert at least one message of a given type was submitted.
    pub fn assert_sent<M: crate::Mailable>(&self) {
        assert!(
            self.0
                .lock()
                .expect("capture lock")
                .iter()
                .any(CapturedMail::is_type::<M>),
            "Expected mailable was not captured"
        );
    }
    /// Assert delivery to an address without including PII in failure output.
    pub fn assert_sent_to(&self, address: &str) {
        assert!(
            self.0
                .lock()
                .expect("capture lock")
                .iter()
                .any(|m| m.was_sent_to(address)),
            "Expected recipient was not captured"
        );
    }
    /// Assert a subject without including message data in failure output.
    pub fn assert_subject(&self, subject: &str) {
        assert!(
            self.0
                .lock()
                .expect("capture lock")
                .iter()
                .any(|m| m.has_subject(subject)),
            "Expected subject was not captured"
        );
    }
    /// Snapshot captured messages without draining. Explicit accessors inspect content.
    pub fn sent(&self) -> Vec<CapturedMail> {
        self.0.lock().expect("capture lock").clone()
    }
    /// Remove all captured messages.
    pub fn clear(&self) {
        self.0.lock().expect("capture lock").clear();
    }
    /// Drain captured messages; explicit raw MIME access is available on each entry.
    pub fn take(&self) -> Vec<CapturedMail> {
        std::mem::take(&mut *self.0.lock().expect("capture lock"))
    }
}
impl MailTransport for CaptureTransport {
    fn name(&self) -> &'static str {
        "capture"
    }
    fn development_only(&self) -> bool {
        true
    }
    fn send(
        &self,
        mail: PreparedMail,
    ) -> Pin<Box<dyn Future<Output = MailResult<DeliveryReceipt>> + Send + '_>> {
        Box::pin(async move {
            let mut messages = self.0.lock().map_err(|_| MailError::CaptureFull)?;
            let captured = CapturedMail::from_prepared(mail);
            let bytes = captured.bytes();
            let retained: usize = messages.iter().map(CapturedMail::bytes).sum();
            if messages.len() >= 100 || retained.saturating_add(bytes) > 64 * 1024 * 1024 {
                return Err(MailError::CaptureFull);
            }
            let receipt = DeliveryReceipt {
                message_id: captured.message_id().to_owned(),
                provider_id: None,
            };
            messages.push(captured);
            Ok(receipt)
        })
    }
}