use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use rustls::pki_types::CertificateDer;
use super::tls::Tls;
use super::{
DeliveryEvent, DeliveryLog, DeliveryStats, EmailDriver, InboxPage, OutboundEmail, SentEmail,
imap, mime, smtp,
};
use crate::error::{DriverError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MailSecurity {
Tls,
StartTls,
Plain,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MailEndpoint {
pub host: String,
pub port: u16,
pub security: MailSecurity,
pub timeout: Duration,
}
impl MailEndpoint {
fn new(host: &str, port: u16, security: MailSecurity) -> Result<Self> {
let host = host.trim().to_string();
if host.is_empty() {
return Err(DriverError::invalid("a mail server needs a host"));
}
Ok(Self { host, port, security, timeout: Duration::from_secs(30) })
}
pub fn tls(host: &str, port: u16) -> Result<Self> {
Self::new(host, port, MailSecurity::Tls)
}
pub fn starttls(host: &str, port: u16) -> Result<Self> {
Self::new(host, port, MailSecurity::StartTls)
}
pub fn plain(host: &str, port: u16) -> Result<Self> {
let loopback = host == "localhost"
|| host
.trim_matches(['[', ']'])
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback());
if !loopback {
return Err(DriverError::invalid(format!(
"`{host}` is not loopback; use TLS or STARTTLS for a mail server on a network"
)));
}
Self::new(host, port, MailSecurity::Plain)
}
#[must_use]
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
}
#[derive(Clone)]
pub(crate) struct Secret(String);
impl Secret {
pub(crate) fn expose(&self) -> &str {
&self.0
}
}
impl std::fmt::Debug for Secret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("[redacted]")
}
}
#[derive(Debug, Clone)]
pub(crate) struct Credentials {
pub(crate) username: String,
pub(crate) password: Secret,
}
pub struct ImapSmtpEmail {
imap: MailEndpoint,
smtp: MailEndpoint,
credentials: Credentials,
mailbox: String,
helo: String,
tls: Tls,
log: DeliveryLog,
}
impl std::fmt::Debug for ImapSmtpEmail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ImapSmtpEmail")
.field("imap", &self.imap)
.field("smtp", &self.smtp)
.field("username", &self.credentials.username)
.field("mailbox", &self.mailbox)
.finish_non_exhaustive()
}
}
impl ImapSmtpEmail {
pub fn new(
imap: MailEndpoint,
smtp: MailEndpoint,
username: &str,
password: impl Into<String>,
) -> Result<Self> {
let password = password.into();
if username.trim().is_empty() || password.is_empty() {
return Err(DriverError::invalid("an email account needs a user name and a password"));
}
let helo = username
.rsplit('@')
.next()
.filter(|domain| domain.contains('.'))
.unwrap_or("localhost")
.to_string();
Ok(Self {
imap,
smtp,
credentials: Credentials {
username: username.trim().to_string(),
password: Secret(password),
},
mailbox: "INBOX".to_string(),
helo,
tls: Tls::new(&[])?,
log: DeliveryLog::default(),
})
}
#[must_use]
pub fn with_mailbox(mut self, mailbox: impl Into<String>) -> Self {
self.mailbox = mailbox.into();
self
}
pub fn with_root_certificate(mut self, der: Vec<u8>) -> Result<Self> {
self.tls = Tls::new(&[CertificateDer::from(der)])?;
Ok(self)
}
}
fn parse_cursor(cursor: &str) -> Result<(u32, u32)> {
let parsed = cursor
.split_once(':')
.and_then(|(validity, uid)| Some((validity.parse().ok()?, uid.parse().ok()?)));
parsed
.ok_or_else(|| DriverError::invalid(format!("`{cursor}` is not a cursor this driver gave")))
}
#[async_trait]
impl EmailDriver for ImapSmtpEmail {
fn name(&self) -> &str {
"imap-smtp"
}
async fn inbox(&self, cursor: Option<&str>, limit: usize) -> Result<InboxPage> {
let after = cursor.map(parse_cursor).transpose()?;
let read =
imap::read(&self.imap, &self.credentials, &self.tls, &self.mailbox, after, limit)
.await?;
let last = match (read.messages.last(), after) {
(Some(message), _) => message.uid,
(None, Some((validity, uid))) if validity == read.uid_validity => uid,
(None, _) => 0,
};
let messages: Vec<_> = read
.messages
.iter()
.map(|fetched| {
let fallback = format!("{}.{}@imap.invalid", fetched.uid, read.uid_validity);
mime::parse_message(
&fetched.raw,
fetched.received_at.unwrap_or_else(Utc::now),
&fallback,
)
})
.collect();
self.log.record_reports(&messages);
Ok(InboxPage { messages, cursor: Some(format!("{}:{last}", read.uid_validity)) })
}
async fn send(&self, message: &OutboundEmail) -> Result<SentEmail> {
let at = Utc::now();
let wire = mime::render_message(message, at)?;
let recipients: Vec<String> =
message.to.iter().map(|mailbox| mailbox.address.clone()).collect();
let submitted = smtp::submit(
&self.smtp,
&self.credentials,
&self.tls,
&self.helo,
&message.from.address,
&recipients,
&wire,
)
.await;
let submitted = match submitted {
Ok(submitted) => submitted,
Err(error) => {
if matches!(error, DriverError::Refused { .. }) {
for _ in &recipients {
self.log.record(DeliveryEvent::Rejected, at);
}
}
return Err(error);
}
};
for _ in &submitted.rejected {
self.log.record(DeliveryEvent::Rejected, at);
}
self.log.record(DeliveryEvent::Sent, at);
Ok(SentEmail { message_id: message.message_id.clone(), accepted: submitted.accepted, at })
}
async fn delivery_stats(
&self,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> Result<DeliveryStats> {
Ok(self.log.stats(from, to))
}
}