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;
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};
pub type MailResult<T> = Result<T, MailError>;
#[derive(Clone, Debug)]
pub struct MailObservation {
pub event: &'static str,
pub message_type: String,
pub transport: &'static str,
pub duration: Duration,
pub queue_job_id: Option<String>,
pub error_category: Option<&'static str>,
}
pub trait MailObserver: Send + Sync + 'static {
fn observe(&self, observation: &MailObservation);
}
#[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 {
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(())
}
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))
}
pub fn capture(config: &AppConfig) -> capy_core::Result<(Self, CaptureTransport)> {
let capture = CaptureTransport::new();
Ok((Self::with_transport(config, capture.clone())?, capture))
}
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,
})
}
pub fn development_only(&self) -> bool {
self.transport.development_only()
}
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(())
}
pub fn observe(mut self, observer: impl MailObserver) -> Self {
self.observer = Some(Arc::new(observer));
self
}
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)
}
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
}
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())
});
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(())
}
}
#[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;