use crate::{CapturedMail, MailError, MailResult, Mailbox};
use lettre::{AsyncTransport, Tokio1Executor};
use std::{
future::Future,
pin::Pin,
sync::{Arc, Mutex},
};
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 {
pub fn message(&self) -> &lettre::Message {
&self.message
}
pub fn message_type(&self) -> &str {
&self.message_type
}
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])")
}
}
#[derive(Clone)]
pub struct DeliveryReceipt {
pub message_id: String,
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])")
}
}
pub trait MailTransport: Send + Sync + 'static {
fn name(&self) -> &'static str;
fn development_only(&self) -> bool {
false
}
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 {
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
}
}
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,
})
})
}
}
#[derive(Clone, Default)]
pub struct CaptureTransport(Arc<Mutex<Vec<CapturedMail>>>);
impl CaptureTransport {
pub fn new() -> Self {
Self::default()
}
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"
);
}
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"
);
}
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"
);
}
pub fn sent(&self) -> Vec<CapturedMail> {
self.0.lock().expect("capture lock").clone()
}
pub fn clear(&self) {
self.0.lock().expect("capture lock").clear();
}
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)
})
}
}