capy-mail 0.10.0

Conventional SMTP mail, typed templates, and mail notifications for Capy.
Documentation
use crate::{MailError, MailResult};
use lettre::message::{
    header::{ContentType, HeaderName, HeaderValue},
    Attachment as MimeAttachment, MultiPart, SinglePart,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::str::FromStr;

/// A parsed mailbox; debug output never reveals the address or display name.
#[derive(Clone)]
pub struct Mailbox(pub(crate) lettre::message::Mailbox);
impl Mailbox {
    /// Parse one address, optionally with a display name. Reject all header controls.
    pub fn parse(value: &str) -> MailResult<Self> {
        header_text(value)?;
        value.parse().map(Self).map_err(|_| MailError::Address)
    }
    /// Construct a mailbox from separately supplied address and display name.
    pub fn new(address: &str, name: Option<String>) -> MailResult<Self> {
        header_text(address)?;
        if let Some(name) = &name {
            header_text(name)?;
        }
        Ok(Self(lettre::message::Mailbox::new(
            name,
            address.parse().map_err(|_| MailError::Address)?,
        )))
    }
    /// Explicit address access for routing or application tests; do not log it.
    pub fn address(&self) -> String {
        self.0.email.to_string()
    }
}
impl FromStr for Mailbox {
    type Err = MailError;
    fn from_str(value: &str) -> MailResult<Self> {
        Self::parse(value)
    }
}
impl Serialize for Mailbox {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.to_string().serialize(serializer)
    }
}
impl<'de> Deserialize<'de> for Mailbox {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Self::parse(&String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
    }
}
impl std::fmt::Debug for Mailbox {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Mailbox([REDACTED])")
    }
}

/// An in-memory attachment. No path is opened implicitly; applications own file access.
#[derive(Clone)]
pub struct Attachment {
    pub(crate) filename: String,
    pub(crate) content_type: ContentType,
    pub(crate) bytes: Vec<u8>,
}
impl Attachment {
    /// Validate metadata and take ownership of bounded content (at most 10 MiB).
    /// The mailer's aggregate message limit is checked separately before MIME encoding.
    pub fn new(filename: impl Into<String>, mime_type: &str, bytes: Vec<u8>) -> MailResult<Self> {
        let filename = filename.into();
        header_text(&filename)?;
        if filename.is_empty()
            || filename.len() > 255
            || filename.contains(['/', '\\'])
            || bytes.len() > 10 * 1024 * 1024
        {
            return Err(MailError::Attachment);
        }
        header_text(mime_type)?;
        let content_type = ContentType::parse(mime_type).map_err(|_| MailError::Attachment)?;
        Ok(Self {
            filename,
            content_type,
            bytes,
        })
    }
}
impl std::fmt::Debug for Attachment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Attachment([REDACTED])")
    }
}

/// Application-owned content. It is deliberately not serializable.
#[derive(Clone, Default)]
pub struct Mail {
    pub(crate) from: Option<Mailbox>,
    pub(crate) to: Vec<Mailbox>,
    pub(crate) cc: Vec<Mailbox>,
    pub(crate) bcc: Vec<Mailbox>,
    pub(crate) reply_to: Option<Mailbox>,
    pub(crate) subject: String,
    pub(crate) text: Option<String>,
    pub(crate) html: Option<String>,
    pub(crate) attachments: Vec<Attachment>,
    pub(crate) headers: Vec<(String, String)>,
}
impl std::fmt::Debug for Mail {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Mail([REDACTED])")
    }
}
impl Mail {
    /// Begin a message. Header values and body bounds are checked before transport.
    pub fn new(subject: impl Into<String>) -> Self {
        Self {
            subject: subject.into(),
            ..Self::default()
        }
    }
    /// Set the plain-text alternative.
    pub fn text(mut self, body: impl Into<String>) -> Self {
        self.text = Some(body.into());
        self
    }
    /// Set the HTML alternative. Escape untrusted content with a template engine.
    pub fn html(mut self, body: impl Into<String>) -> Self {
        self.html = Some(body.into());
        self
    }
    /// Override the configured sender with a parsed mailbox.
    pub fn from(mut self, mailbox: Mailbox) -> Self {
        self.from = Some(mailbox);
        self
    }
    /// Add an explicit parsed recipient.
    pub fn to(mut self, mailbox: Mailbox) -> Self {
        self.to.push(mailbox);
        self
    }
    /// Add a carbon-copy recipient.
    pub fn cc(mut self, mailbox: Mailbox) -> Self {
        self.cc.push(mailbox);
        self
    }
    /// Add an envelope-only recipient; Bcc is removed from the transmitted MIME message.
    pub fn bcc(mut self, mailbox: Mailbox) -> Self {
        self.bcc.push(mailbox);
        self
    }
    /// Set a reply address.
    pub fn reply_to(mut self, mailbox: Mailbox) -> Self {
        self.reply_to = Some(mailbox);
        self
    }
    /// Attach already-loaded bytes; queueing attachments requires an application-owned job.
    pub fn attach(mut self, attachment: Attachment) -> Self {
        self.attachments.push(attachment);
        self
    }
    /// Add a custom X-* header. Standard routing/MIME headers use typed builder methods.
    pub fn header(mut self, name: &str, value: impl Into<String>) -> MailResult<Self> {
        let value = value.into();
        validate_header(name, &value)?;
        self.headers.push((name.into(), value));
        Ok(self)
    }
    pub(crate) fn build(
        self,
        default_from: &Mailbox,
        max_bytes: usize,
        id: &str,
    ) -> MailResult<lettre::Message> {
        header_text(&self.subject)?;
        if self.subject.len() > 998
            || self.to.len() + self.cc.len() + self.bcc.len() == 0
            || self.to.len() + self.cc.len() + self.bcc.len() > 100
            || self.attachments.len() > 20
            || self.headers.len() > 32
            || (self.text.is_none() && self.html.is_none())
        {
            return Err(MailError::Message);
        }
        let bytes = self
            .text
            .as_ref()
            .map_or(0, String::len)
            .saturating_add(self.html.as_ref().map_or(0, String::len));
        let bytes = self
            .attachments
            .iter()
            .fold(bytes, |n, a| n.saturating_add(a.bytes.len()));
        if bytes > max_bytes {
            return Err(MailError::Size);
        }
        let mut builder = lettre::Message::builder()
            .from(self.from.unwrap_or_else(|| default_from.clone()).0)
            .subject(self.subject)
            .message_id(Some(id.into()));
        for recipient in self.to {
            builder = builder.to(recipient.0);
        }
        for recipient in self.cc {
            builder = builder.cc(recipient.0);
        }
        for recipient in self.bcc {
            builder = builder.bcc(recipient.0);
        }
        if let Some(reply) = self.reply_to {
            builder = builder.reply_to(reply.0);
        }
        for (name, value) in self.headers {
            validate_header(&name, &value)?;
            builder = builder.raw_header(HeaderValue::new(
                HeaderName::new_from_ascii(name).map_err(|_| MailError::Header)?,
                value,
            ));
        }
        let content = match (self.text, self.html) {
            (Some(text), Some(html)) => MultiPart::alternative_plain_html(text, html),
            (Some(text), None) => MultiPart::mixed().singlepart(SinglePart::plain(text)),
            (None, Some(html)) => MultiPart::mixed().singlepart(SinglePart::html(html)),
            _ => return Err(MailError::Message),
        };
        let content = if self.attachments.is_empty() {
            content
        } else {
            self.attachments.into_iter().fold(
                MultiPart::mixed().multipart(content),
                |parts, attachment| {
                    parts.singlepart(
                        MimeAttachment::new(attachment.filename)
                            .body(attachment.bytes, attachment.content_type),
                    )
                },
            )
        };
        builder.multipart(content).map_err(|_| MailError::Message)
    }
}
pub(crate) fn header_text(value: &str) -> MailResult<()> {
    if value.chars().any(char::is_control) || value.len() > 4096 {
        Err(MailError::Header)
    } else {
        Ok(())
    }
}
fn validate_header(name: &str, value: &str) -> MailResult<()> {
    if !name.to_ascii_lowercase().starts_with("x-")
        || name.len() > 78
        || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
    {
        return Err(MailError::Header);
    }
    HeaderName::new_from_ascii(name.into()).map_err(|_| MailError::Header)?;
    header_text(value)
}

/// Typed application template/context; business code remains ordinary Rust.
pub trait Mailable: Send + Sync {
    /// Stable safe diagnostic name, independent of Rust module paths.
    const NAME: &'static str;
    /// Render real text/HTML content before message validation and transport.
    fn render(&self) -> MailResult<Mail>;
    /// Parse an address before any transport activity.
    fn to(self, address: impl AsRef<str>) -> MailResult<Envelope<Self>>
    where
        Self: Sized,
    {
        Ok(Envelope {
            content: self,
            recipient: Mailbox::parse(address.as_ref())?,
        })
    }
    /// Address content with an already parsed mailbox.
    fn to_mailbox(self, recipient: Mailbox) -> Envelope<Self>
    where
        Self: Sized,
    {
        Envelope {
            content: self,
            recipient,
        }
    }
}
/// A typed mailable and parsed primary recipient. Debug is redacted.
pub struct Envelope<M> {
    pub(crate) content: M,
    pub(crate) recipient: Mailbox,
}
impl<M> std::fmt::Debug for Envelope<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Envelope([REDACTED])")
    }
}

/// Explicit assertion that this mailable contains no secrets or private attachments.
/// Implement only after reviewing rendered text/HTML, headers and addresses for storage
/// in plaintext queue rows/backups. There is deliberately no blanket implementation.
/// Implement as `impl QueueableMail for WelcomeMail {}` only after reviewing the
/// complete rendered output. Use `mailer.queue(&ctx, welcome.to(address)?).await?`
/// for ordinary content, or `queue_in` for transactionally safe enqueue. Secrets
/// such as reset/activation links and private attachments must use direct delivery
/// or an application-owned protected outbox instead. Queueing is at least once;
/// a successful SMTP send can still be repeated after a worker crash.
pub trait QueueableMail: Mailable {}