use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
use base64::Engine as _;
use serde_json::json;
use super::{Delivery, Mail, split_address};
use crate::config::Config;
use crate::error::{Error, Result};
type Sending<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
pub struct Inbox;
const INBOX_SIZE: usize = 100;
type Kept = (u64, chrono::DateTime<chrono::Utc>, Mail);
static INBOX: Mutex<Vec<Kept>> = Mutex::new(Vec::new());
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
impl Inbox {
pub fn mails() -> Vec<Kept> {
let mut mails = INBOX.lock().unwrap_or_else(|e| e.into_inner()).clone();
mails.reverse();
mails
}
pub fn clear() {
INBOX.lock().unwrap_or_else(|e| e.into_inner()).clear();
}
}
impl Delivery for Inbox {
fn name(&self) -> &'static str {
"inbox"
}
fn deliver<'a>(&'a self, mail: &'a Mail) -> Sending<'a> {
let mut inbox = INBOX.lock().unwrap_or_else(|e| e.into_inner());
let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
inbox.push((id, chrono::Utc::now(), mail.clone()));
let excess = inbox.len().saturating_sub(INBOX_SIZE);
inbox.drain(..excess);
tracing::info!(
target: "glacier::mail",
to = %mail.to.join(", "),
subject = %mail.subject,
"kept in the development inbox: read it at /dev/mail"
);
Box::pin(async { Ok(()) })
}
}
pub struct Smtp {
transport: lettre::AsyncSmtpTransport<lettre::Tokio1Executor>,
}
impl Smtp {
pub fn from_config(config: &Config) -> Result<Self> {
let host: String = config.get("mail.smtp.host")?;
let tls = config
.get_opt::<String>("mail.smtp.tls")?
.unwrap_or_else(|| "starttls".to_owned());
type Transport = lettre::AsyncSmtpTransport<lettre::Tokio1Executor>;
let smtp_error =
|e: lettre::transport::smtp::Error| Error::internal(format!("mail.smtp: {e}"));
let (builder, default_port) = match tls.as_str() {
"starttls" => (Transport::starttls_relay(&host).map_err(smtp_error)?, 587),
"tls" => (Transport::relay(&host).map_err(smtp_error)?, 465),
"none" => (Transport::builder_dangerous(&host), 25),
other => {
return Err(Error::internal(format!(
"mail.smtp.tls `{other}`: expected starttls, tls or none"
)));
}
};
let port = config
.get_opt::<u16>("mail.smtp.port")?
.unwrap_or(default_port);
let mut builder = builder.port(port);
if let Some(username) = config.get_opt::<String>("mail.smtp.username")? {
let password = config
.get_opt::<String>("mail.smtp.password")?
.unwrap_or_default();
builder = builder.credentials(
lettre::transport::smtp::authentication::Credentials::new(username, password),
);
}
Ok(Self {
transport: builder.build(),
})
}
}
impl Delivery for Smtp {
fn name(&self) -> &'static str {
"smtp"
}
fn deliver<'a>(&'a self, mail: &'a Mail) -> Sending<'a> {
Box::pin(async move {
use lettre::AsyncTransport as _;
let message = mime_message(mail)?;
self.transport
.send(message)
.await
.map_err(|e| Error::internal(format!("sending mail by SMTP: {e}")))?;
Ok(())
})
}
}
pub(crate) fn mime_message(mail: &Mail) -> Result<lettre::Message> {
use lettre::message::header::{ContentType, HeaderName, HeaderValue};
use lettre::message::{Attachment, MultiPart, SinglePart};
let address = |text: &str| -> Result<lettre::message::Mailbox> {
text.parse()
.map_err(|e| Error::internal(format!("mail address `{text}`: {e}")))
};
let mut builder = lettre::Message::builder().subject(mail.subject.clone());
if let Some(from) = &mail.from {
builder = builder.from(address(from)?);
}
for to in &mail.to {
builder = builder.to(address(to)?);
}
for cc in &mail.cc {
builder = builder.cc(address(cc)?);
}
for bcc in &mail.bcc {
builder = builder.bcc(address(bcc)?);
}
if let Some(reply_to) = &mail.reply_to {
builder = builder.reply_to(address(reply_to)?);
}
for (name, value) in &mail.headers {
builder = builder.raw_header(HeaderValue::new(
HeaderName::new_from_ascii(name.clone())
.map_err(|_| Error::internal(format!("mail header name `{name}`")))?,
value.clone(),
));
}
let content_type = |text: &str| {
ContentType::parse(text).map_err(|_| Error::internal(format!("attachment type `{text}`")))
};
let html = match &mail.html {
Some(html) => {
let inline: Vec<_> = mail
.attachments
.iter()
.filter(|f| f.content_id.is_some())
.collect();
if inline.is_empty() {
Some(MultiPart::mixed().singlepart(SinglePart::html(html.clone())))
} else {
let mut related = MultiPart::related().singlepart(SinglePart::html(html.clone()));
for file in inline {
let cid = file.content_id.clone().unwrap_or_default();
related = related.singlepart(
Attachment::new_inline(cid)
.body(file.data.clone(), content_type(&file.content_type)?),
);
}
Some(related)
}
}
None => None,
};
let body = match (&mail.text, html) {
(Some(text), Some(_)) if !mail.attachments.iter().any(|f| f.content_id.is_some()) => {
MultiPart::alternative_plain_html(text.clone(), mail.html.clone().unwrap_or_default())
}
(Some(text), Some(html)) => MultiPart::alternative()
.singlepart(SinglePart::plain(text.clone()))
.multipart(html),
(Some(text), None) => MultiPart::mixed().singlepart(SinglePart::plain(text.clone())),
(None, Some(html)) => html,
(None, None) => MultiPart::mixed().singlepart(SinglePart::plain(String::new())),
};
let files: Vec<_> = mail
.attachments
.iter()
.filter(|f| f.content_id.is_none())
.collect();
let body = if files.is_empty() {
body
} else {
let mut mixed = MultiPart::mixed().multipart(body);
for file in files {
mixed = mixed.singlepart(
Attachment::new(file.filename.clone())
.body(file.data.clone(), content_type(&file.content_type)?),
);
}
mixed
};
builder
.multipart(body)
.map_err(|e| Error::internal(format!("building the mail: {e}")))
}
pub struct SendGrid {
api_key: String,
endpoint: String,
client: reqwest::Client,
}
impl SendGrid {
pub fn from_config(config: &Config) -> Result<Self> {
Ok(Self {
api_key: config.get("mail.sendgrid.api_key")?,
endpoint: config
.get_opt("mail.sendgrid.endpoint")?
.unwrap_or_else(|| "https://api.sendgrid.com/v3/mail/send".to_owned()),
client: reqwest::Client::new(),
})
}
pub fn payload(mail: &Mail) -> serde_json::Value {
let email = |text: &String| {
let (name, address) = split_address(text);
match name {
Some(name) => json!({"email": address, "name": name}),
None => json!({"email": address}),
}
};
let mut personalization = serde_json::Map::new();
for (key, list) in [("to", &mail.to), ("cc", &mail.cc), ("bcc", &mail.bcc)] {
if !list.is_empty() {
personalization.insert(key.into(), list.iter().map(email).collect());
}
}
let mut content = Vec::new();
if let Some(text) = &mail.text {
content.push(json!({"type": "text/plain", "value": text}));
}
if let Some(html) = &mail.html {
content.push(json!({"type": "text/html", "value": html}));
}
let mut body = json!({
"personalizations": [personalization],
"from": mail.from.as_ref().map(email),
"subject": mail.subject,
"content": content,
});
if let Some(reply_to) = &mail.reply_to {
body["reply_to"] = email(reply_to);
}
if !mail.headers.is_empty() {
body["headers"] = mail
.headers
.iter()
.map(|(k, v)| (k.clone(), json!(v)))
.collect::<serde_json::Map<_, _>>()
.into();
}
if !mail.attachments.is_empty() {
body["attachments"] = mail
.attachments
.iter()
.map(|file| {
let mut part = json!({
"content": base64::engine::general_purpose::STANDARD.encode(&file.data),
"filename": file.filename,
"type": file.content_type,
"disposition": "attachment",
});
if let Some(cid) = &file.content_id {
part["disposition"] = json!("inline");
part["content_id"] = json!(cid);
}
part
})
.collect();
}
body
}
}
impl Delivery for SendGrid {
fn name(&self) -> &'static str {
"sendgrid"
}
fn deliver<'a>(&'a self, mail: &'a Mail) -> Sending<'a> {
Box::pin(async move {
let res = self
.client
.post(&self.endpoint)
.bearer_auth(&self.api_key)
.header("Content-Type", "application/json")
.body(Self::payload(mail).to_string())
.send()
.await
.map_err(|e| Error::internal(format!("sending mail by SendGrid: {e}")))?;
refused("SendGrid", res).await
})
}
}
pub struct Postmark {
token: String,
stream: String,
endpoint: String,
client: reqwest::Client,
}
impl Postmark {
pub fn from_config(config: &Config) -> Result<Self> {
Ok(Self {
token: config.get("mail.postmark.server_token")?,
stream: config
.get_opt("mail.postmark.stream")?
.unwrap_or_else(|| "outbound".to_owned()),
endpoint: config
.get_opt("mail.postmark.endpoint")?
.unwrap_or_else(|| "https://api.postmarkapp.com/email".to_owned()),
client: reqwest::Client::new(),
})
}
pub fn payload(mail: &Mail, stream: &str) -> serde_json::Value {
let mut body = json!({
"From": mail.from,
"To": mail.to.join(", "),
"Subject": mail.subject,
"MessageStream": stream,
});
let optional = [
("Cc", (!mail.cc.is_empty()).then(|| mail.cc.join(", "))),
("Bcc", (!mail.bcc.is_empty()).then(|| mail.bcc.join(", "))),
("ReplyTo", mail.reply_to.clone()),
("HtmlBody", mail.html.clone()),
("TextBody", mail.text.clone()),
];
for (key, value) in optional {
if let Some(value) = value {
body[key] = json!(value);
}
}
if !mail.headers.is_empty() {
body["Headers"] = mail
.headers
.iter()
.map(|(name, value)| json!({"Name": name, "Value": value}))
.collect();
}
if !mail.attachments.is_empty() {
body["Attachments"] = mail
.attachments
.iter()
.map(|file| {
let mut part = json!({
"Name": file.filename,
"Content": base64::engine::general_purpose::STANDARD.encode(&file.data),
"ContentType": file.content_type,
});
if let Some(cid) = &file.content_id {
part["ContentID"] = json!(format!("cid:{cid}"));
}
part
})
.collect();
}
body
}
}
impl Delivery for Postmark {
fn name(&self) -> &'static str {
"postmark"
}
fn deliver<'a>(&'a self, mail: &'a Mail) -> Sending<'a> {
Box::pin(async move {
let res = self
.client
.post(&self.endpoint)
.header("X-Postmark-Server-Token", &self.token)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.body(Self::payload(mail, &self.stream).to_string())
.send()
.await
.map_err(|e| Error::internal(format!("sending mail by Postmark: {e}")))?;
refused("Postmark", res).await
})
}
}
async fn refused(service: &str, res: reqwest::Response) -> Result<()> {
let status = res.status();
if status.is_success() {
return Ok(());
}
let said = res.text().await.unwrap_or_default();
let said: String = said.chars().take(500).collect();
Err(Error::internal(format!(
"{service} refused the mail ({status}): {said}"
)))
}
#[cfg(test)]
mod tests {
use super::*;
fn mail() -> Mail {
Mail::new()
.from("Reports <reports@example.com>")
.to("ada@example.com")
.cc("Bo <bo@example.com>")
.subject("Ready")
.text("Your report is ready.")
.html("<p>Your report is ready.</p>")
.attach("r.txt", "text/plain", b"hi".to_vec())
.header("X-Tag", "reports")
}
#[test]
fn sendgrid_payload() {
let body = SendGrid::payload(&mail());
assert_eq!(
body["from"],
json!({"email": "reports@example.com", "name": "Reports"})
);
assert_eq!(
body["personalizations"][0]["to"],
json!([{"email": "ada@example.com"}])
);
assert_eq!(
body["personalizations"][0]["cc"],
json!([{"email": "bo@example.com", "name": "Bo"}])
);
assert_eq!(body["content"][0]["type"], "text/plain");
assert_eq!(body["content"][1]["value"], "<p>Your report is ready.</p>");
assert_eq!(body["attachments"][0]["content"], "aGk=");
assert_eq!(body["headers"]["X-Tag"], "reports");
}
#[test]
fn postmark_payload() {
let body = Postmark::payload(&mail(), "outbound");
assert_eq!(body["From"], "Reports <reports@example.com>");
assert_eq!(body["Cc"], "Bo <bo@example.com>");
assert_eq!(body["TextBody"], "Your report is ready.");
assert_eq!(body["Attachments"][0]["Name"], "r.txt");
assert_eq!(
body["Headers"][0],
json!({"Name": "X-Tag", "Value": "reports"})
);
assert!(body.get("Bcc").is_none());
}
#[test]
fn inline_images_go_with_the_html() {
let mail = mail().attach_inline("logo.png", "image/png", vec![1, 2, 3]);
let text = String::from_utf8(mime_message(&mail).unwrap().formatted()).unwrap();
assert!(text.contains("multipart/related"), "{text}");
assert!(text.contains("Content-ID: <logo.png>"), "{text}");
assert!(
text.contains("filename=\"r.txt\""),
"the other file stays an attachment"
);
let sendgrid = SendGrid::payload(&mail);
assert_eq!(sendgrid["attachments"][1]["disposition"], "inline");
assert_eq!(sendgrid["attachments"][1]["content_id"], "logo.png");
assert_eq!(
Postmark::payload(&mail, "outbound")["Attachments"][1]["ContentID"],
"cid:logo.png"
);
}
#[test]
fn mime_has_alternatives_and_attachments() {
let text = String::from_utf8(mime_message(&mail()).unwrap().formatted()).unwrap();
assert!(text.contains("Subject: Ready"), "{text}");
assert!(text.contains("multipart/alternative"), "{text}");
assert!(text.contains("filename=\"r.txt\""), "{text}");
assert!(text.contains("X-Tag: reports"), "{text}");
}
}