mod deliveries;
pub mod preview;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, RwLock};
use serde::{Deserialize, Serialize};
pub use self::deliveries::{Inbox, Postmark, SendGrid, Smtp};
pub use self::preview::Previews;
use crate::config::{Config, Env};
use crate::error::{Error, Result};
use crate::jobs::Job;
use crate::view::{Rendered, Template};
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Mail {
pub from: Option<String>,
pub to: Vec<String>,
pub cc: Vec<String>,
pub bcc: Vec<String>,
pub reply_to: Option<String>,
pub subject: String,
pub html: Option<String>,
pub text: Option<String>,
pub attachments: Vec<Attachment>,
pub headers: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Attachment {
pub filename: String,
pub content_type: String,
#[serde(with = "base64_bytes")]
pub data: Vec<u8>,
#[serde(default)]
pub content_id: Option<String>,
}
pub trait Body {
fn into_body(self) -> String;
}
impl<T: Template> Body for T {
fn into_body(self) -> String {
self.render().to_html()
}
}
impl Body for Rendered {
fn into_body(self) -> String {
self.to_html()
}
}
impl Body for String {
fn into_body(self) -> String {
self
}
}
impl Body for &str {
fn into_body(self) -> String {
self.to_owned()
}
}
impl Mail {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn from(mut self, address: impl Into<String>) -> Self {
self.from = Some(address.into());
self
}
#[must_use]
pub fn to(mut self, address: impl Into<String>) -> Self {
self.to.push(address.into());
self
}
#[must_use]
pub fn cc(mut self, address: impl Into<String>) -> Self {
self.cc.push(address.into());
self
}
#[must_use]
pub fn bcc(mut self, address: impl Into<String>) -> Self {
self.bcc.push(address.into());
self
}
#[must_use]
pub fn reply_to(mut self, address: impl Into<String>) -> Self {
self.reply_to = Some(address.into());
self
}
#[must_use]
pub fn subject(mut self, subject: impl Into<String>) -> Self {
self.subject = subject.into();
self
}
#[must_use]
pub fn html(mut self, body: impl Body) -> Self {
self.html = Some(body.into_body());
self
}
#[must_use]
pub fn text(mut self, body: impl Body) -> Self {
self.text = Some(body.into_body());
self
}
#[must_use]
pub fn attach(
mut self,
filename: impl Into<String>,
content_type: impl Into<String>,
data: impl Into<Vec<u8>>,
) -> Self {
self.attachments.push(Attachment {
filename: filename.into(),
content_type: content_type.into(),
data: data.into(),
content_id: None,
});
self
}
#[must_use]
pub fn attach_inline(
mut self,
filename: impl Into<String>,
content_type: impl Into<String>,
data: impl Into<Vec<u8>>,
) -> Self {
let filename = filename.into();
self.attachments.push(Attachment {
content_id: Some(filename.clone()),
filename,
content_type: content_type.into(),
data: data.into(),
});
self
}
#[must_use]
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub async fn deliver_now(self) -> Result<()> {
let mail = self.ready()?;
let delivery = current();
let span = tracing::info_span!(
target: "glacier::mail",
"glacier.mail",
otel.name = %format!("mail {}", mail.subject),
otel.kind = "client",
mail.to = %mail.to.join(", "),
mail.subject = %mail.subject,
mail.delivery = delivery.name(),
);
tracing::Instrument::instrument(
async {
delivery.deliver(&mail).await?;
tracing::info!(
target: "glacier::mail",
to = %mail.to.join(", "),
subject = %mail.subject,
"delivered by {}",
delivery.name()
);
Ok(())
},
span,
)
.await
}
pub async fn deliver_later(self) -> Result<i64> {
DeliverMail(self.ready()?).enqueue().await
}
fn ready(mut self) -> Result<Self> {
if self.from.is_none() {
self.from = settings().from.clone();
}
if self.from.is_none() {
return Err(Error::internal(
"the mail has no sender: set `from`, or `mail.from` in the config",
));
}
for list in [&mut self.to, &mut self.cc, &mut self.bcc] {
list.retain(|address| !address.trim().is_empty());
}
if self.to.is_empty() && self.cc.is_empty() && self.bcc.is_empty() {
return Err(Error::internal(format!(
"the mail `{}` has no recipients",
self.subject
)));
}
if self.html.is_none() && self.text.is_none() {
return Err(Error::internal(format!(
"the mail `{}` has no body: give it `html` or `text`",
self.subject
)));
}
Ok(self)
}
}
#[derive(Serialize, Deserialize)]
pub struct DeliverMail(pub Mail);
impl Job for DeliverMail {
const NAME: &'static str = "glacier_deliver_mail";
const QUEUE: &'static str = "mailers";
async fn perform(self) -> Result<()> {
self.0.deliver_now().await
}
}
pub trait Delivery: Send + Sync + 'static {
fn name(&self) -> &'static str;
fn deliver<'a>(
&'a self,
mail: &'a Mail,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
}
struct Unconfigured;
impl Delivery for Unconfigured {
fn name(&self) -> &'static str {
"none"
}
fn deliver<'a>(
&'a self,
mail: &'a Mail,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
let subject = mail.subject.clone();
Box::pin(async move {
Err(Error::internal(format!(
"can't send `{subject}`: no mail delivery is configured; set `mail.delivery`"
)))
})
}
}
struct Discard;
impl Delivery for Discard {
fn name(&self) -> &'static str {
"none"
}
fn deliver<'a>(
&'a self,
mail: &'a Mail,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
tracing::info!(target: "glacier::mail", subject = %mail.subject, "not sent: mail.delivery is none");
Box::pin(async { Ok(()) })
}
}
#[derive(Default)]
pub struct TestMailbox;
impl Delivery for TestMailbox {
fn name(&self) -> &'static str {
"test"
}
fn deliver<'a>(
&'a self,
mail: &'a Mail,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
let mail = mail.clone();
Box::pin(async move {
let kept = MAILBOX
.try_with(|mailbox| {
mailbox
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(mail.clone())
})
.is_ok();
if !kept {
SHARED_MAILBOX
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(mail);
}
Ok(())
})
}
}
tokio::task_local! {
static MAILBOX: Arc<Mutex<Vec<Mail>>>;
}
static SHARED_MAILBOX: Mutex<Vec<Mail>> = Mutex::new(Vec::new());
#[doc(hidden)]
pub async fn with_test_mailbox<F: Future>(fut: F) -> F::Output {
MAILBOX.scope(Arc::default(), fut).await
}
pub(crate) fn delivered() -> Vec<Mail> {
MAILBOX
.try_with(|mailbox| mailbox.lock().unwrap_or_else(|e| e.into_inner()).clone())
.unwrap_or_else(|_| {
SHARED_MAILBOX
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
})
}
pub(crate) fn clear_delivered() {
let cleared = MAILBOX
.try_with(|mailbox| mailbox.lock().unwrap_or_else(|e| e.into_inner()).clear())
.is_ok();
if !cleared {
SHARED_MAILBOX
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
}
struct Settings {
from: Option<String>,
delivery: Arc<dyn Delivery>,
chosen: bool,
}
static SETTINGS: RwLock<Option<Arc<Settings>>> = RwLock::new(None);
fn settings() -> Arc<Settings> {
if let Some(settings) = SETTINGS.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
return settings.clone();
}
let settings = Arc::new(Settings {
from: None,
delivery: default_delivery(Env::current()),
chosen: false,
});
*SETTINGS.write().unwrap_or_else(|e| e.into_inner()) = Some(settings.clone());
settings
}
fn current() -> Arc<dyn Delivery> {
if MAILBOX.try_with(|_| ()).is_ok() {
return Arc::new(TestMailbox);
}
settings().delivery.clone()
}
fn default_delivery(env: Env) -> Arc<dyn Delivery> {
match env {
Env::Development => Arc::new(Inbox),
Env::Test => Arc::new(TestMailbox),
Env::Production => Arc::new(Unconfigured),
}
}
pub(crate) fn configure(config: &Config) -> Result<()> {
let from = config.get_opt::<String>("mail.from")?;
let chosen = SETTINGS
.read()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.filter(|settings| settings.chosen)
.map(|settings| settings.delivery.clone());
if let Some(delivery) = chosen {
*SETTINGS.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(Settings {
from,
delivery,
chosen: true,
}));
return Ok(());
}
let delivery: Arc<dyn Delivery> = match config.get_opt::<String>("mail.delivery")?.as_deref() {
None => default_delivery(config.env()),
Some("smtp") => Arc::new(Smtp::from_config(config)?),
Some("sendgrid") => Arc::new(SendGrid::from_config(config)?),
Some("postmark") => Arc::new(Postmark::from_config(config)?),
Some("inbox") => Arc::new(Inbox),
Some("test") => Arc::new(TestMailbox),
Some("none") => Arc::new(Discard),
Some(other) => {
return Err(Error::internal(format!(
"mail.delivery `{other}`: expected smtp, sendgrid, postmark, inbox, test or none"
)));
}
};
*SETTINGS.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(Settings {
from,
delivery,
chosen: false,
}));
Ok(())
}
pub(crate) fn set_delivery(delivery: Arc<dyn Delivery>) {
let from = settings().from.clone();
*SETTINGS.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(Settings {
from,
delivery,
chosen: true,
}));
}
pub(crate) fn split_address(address: &str) -> (Option<&str>, &str) {
match (address.rfind('<'), address.rfind('>')) {
(Some(open), Some(close)) if open < close => {
let name = address[..open].trim().trim_matches('"').trim();
(
(!name.is_empty()).then_some(name),
address[open + 1..close].trim(),
)
}
_ => (None, address.trim()),
}
}
mod base64_bytes {
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&STANDARD.encode(bytes))
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
let text = String::deserialize(d)?;
STANDARD.decode(text).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_addresses() {
assert_eq!(
split_address("Ada <ada@example.com>"),
(Some("Ada"), "ada@example.com")
);
assert_eq!(
split_address("\"Ada L\" <ada@example.com>"),
(Some("Ada L"), "ada@example.com")
);
assert_eq!(split_address("ada@example.com"), (None, "ada@example.com"));
}
#[test]
fn mail_survives_a_job_round_trip() {
let mail = Mail::new()
.to("ada@example.com")
.subject("Hi")
.text("Hello")
.attach("a.bin", "application/octet-stream", vec![0, 255, 7]);
let json = serde_json::to_string(&DeliverMail(mail.clone())).unwrap();
let back: DeliverMail = serde_json::from_str(&json).unwrap();
assert_eq!(back.0, mail);
}
}