use lettre::message::{Mailbox, MultiPart, SinglePart, header::ContentType};
use lettre::transport::smtp::authentication::Credentials;
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use serde::{Deserialize, Serialize};
#[cfg(feature = "mail-templates")]
pub use askama;
#[cfg(feature = "mail-templates")]
pub use askama::Template;
#[derive(Debug, thiserror::Error)]
pub enum MailError {
#[error("render mail template: {0}")]
Template(String),
#[error("invalid address `{0}`")]
Address(String),
#[error("mail config: {0}")]
Config(String),
#[error("build message: {0}")]
Build(String),
#[error("transport: {0}")]
Transport(String),
}
fn is_loopback_host(host: &str) -> bool {
host.eq_ignore_ascii_case("localhost")
|| host
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback())
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct Mail {
pub from: Option<String>,
pub to: Vec<String>,
pub cc: Vec<String>,
pub bcc: Vec<String>,
pub subject: String,
pub text: Option<String>,
pub html: Option<String>,
}
impl Mail {
pub fn new() -> Self {
Self::default()
}
pub fn from(mut self, a: impl Into<String>) -> Self {
self.from = Some(a.into());
self
}
pub fn to(mut self, a: impl Into<String>) -> Self {
self.to.push(a.into());
self
}
pub fn cc(mut self, a: impl Into<String>) -> Self {
self.cc.push(a.into());
self
}
pub fn bcc(mut self, a: impl Into<String>) -> Self {
self.bcc.push(a.into());
self
}
pub fn subject(mut self, s: impl Into<String>) -> Self {
self.subject = s.into();
self
}
pub fn text(mut self, b: impl Into<String>) -> Self {
self.text = Some(b.into());
self
}
pub fn html(mut self, b: impl Into<String>) -> Self {
self.html = Some(b.into());
self
}
#[cfg(feature = "mail-templates")]
pub fn html_template<T: Template>(self, t: &T) -> Result<Self, MailError> {
let body = t.render().map_err(|e| MailError::Template(e.to_string()))?;
Ok(self.html(body))
}
#[cfg(feature = "mail-templates")]
pub fn text_template<T: Template>(self, t: &T) -> Result<Self, MailError> {
let body = t.render().map_err(|e| MailError::Template(e.to_string()))?;
Ok(self.text(body))
}
}
#[derive(Clone, PartialEq)]
pub struct SmtpConfig {
pub host: String,
pub port: u16,
pub username: Option<String>,
pub password: Option<String>,
}
impl std::fmt::Debug for SmtpConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SmtpConfig")
.field("host", &self.host)
.field("port", &self.port)
.field("username", &self.username)
.field("password", &self.password.as_ref().map(|_| "<redacted>"))
.finish()
}
}
#[derive(Debug, Clone, PartialEq)]
enum Driver {
Log,
Smtp(SmtpConfig),
}
#[derive(Clone)]
pub struct Mailer {
from: String,
#[allow(dead_code)] driver: Driver,
smtp: Option<AsyncSmtpTransport<Tokio1Executor>>,
}
fn mbox(a: &str) -> Result<Mailbox, MailError> {
a.trim()
.parse()
.map_err(|_| MailError::Address(a.to_string()))
}
impl Mailer {
pub fn log(from: impl Into<String>) -> Self {
Self {
from: from.into(),
driver: Driver::Log,
smtp: None,
}
}
pub fn smtp(from: impl Into<String>, cfg: SmtpConfig) -> Result<Self, MailError> {
let from = from.into();
mbox(&from)?;
let b = if is_loopback_host(&cfg.host) && cfg.port != 465 {
AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&cfg.host)
} else if cfg.port == 465 {
AsyncSmtpTransport::<Tokio1Executor>::relay(&cfg.host)
.map_err(|e| MailError::Config(e.to_string()))?
} else {
AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&cfg.host)
.map_err(|e| MailError::Config(e.to_string()))?
}
.port(cfg.port);
let b = match (&cfg.username, &cfg.password) {
(Some(u), Some(p)) => b.credentials(Credentials::new(u.clone(), p.clone())),
_ => b,
};
Ok(Self {
from,
driver: Driver::Smtp(cfg),
smtp: Some(b.build()),
})
}
pub fn from_env() -> Result<Self, MailError> {
Self::from_lookup(|k| std::env::var(k).ok())
}
fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self, MailError> {
let from = get("MAIL_FROM").unwrap_or_else(|| "noreply@localhost".into());
match get("MAIL_DRIVER")
.unwrap_or_else(|| "log".into())
.to_lowercase()
.as_str()
{
"log" => Ok(Self::log(from)),
"smtp" => {
let host = get("MAIL_HOST")
.ok_or_else(|| MailError::Config("MAIL_HOST required for smtp".into()))?;
let port = match get("MAIL_PORT") {
Some(p) => p
.parse()
.map_err(|_| MailError::Config(format!("bad MAIL_PORT `{p}`")))?,
None => 587,
};
let nonempty = |k: &str| get(k).filter(|v| !v.is_empty());
Self::smtp(
from,
SmtpConfig {
host,
port,
username: nonempty("MAIL_USERNAME"),
password: nonempty("MAIL_PASSWORD"),
},
)
}
other => Err(MailError::Config(format!("unknown MAIL_DRIVER `{other}`"))),
}
}
fn build(&self, mail: &Mail) -> Result<Message, MailError> {
let mut b = Message::builder().from(mbox(mail.from.as_deref().unwrap_or(&self.from))?);
if mail.to.is_empty() {
return Err(MailError::Build("no recipients".into()));
}
for a in &mail.to {
b = b.to(mbox(a)?);
}
for a in &mail.cc {
b = b.cc(mbox(a)?);
}
for a in &mail.bcc {
b = b.bcc(mbox(a)?);
}
b = b.subject(mail.subject.clone());
match (&mail.text, &mail.html) {
(Some(t), Some(h)) => {
b.multipart(MultiPart::alternative_plain_html(t.clone(), h.clone()))
}
(Some(t), None) => b.singlepart(SinglePart::plain(t.clone())),
(None, Some(h)) => b.singlepart(
SinglePart::builder()
.header(ContentType::TEXT_HTML)
.body(h.clone()),
),
(None, None) => b.body(String::new()),
}
.map_err(|e| MailError::Build(e.to_string()))
}
pub async fn send(&self, mail: Mail) -> Result<(), MailError> {
let msg = self.build(&mail)?; match &self.smtp {
None => {
let body = mail
.text
.as_deref()
.or(mail.html.as_deref())
.unwrap_or_default();
tracing::info!(
"mail (log driver)\nto: {}\nsubject: {}\n\n{body}",
mail.to.join(", "),
mail.subject
);
Ok(())
}
Some(t) => t
.send(msg)
.await
.map(|_| ())
.map_err(|e| MailError::Transport(e.to_string())),
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn debug_never_prints_the_smtp_password() {
let c = SmtpConfig {
host: "smtp.example.com".into(),
port: 587,
username: Some("user".into()),
password: Some("hunter2-secret".into()),
};
let shown = format!("{c:?}");
assert!(!shown.contains("hunter2-secret"), "{shown}");
assert!(shown.contains("smtp.example.com") && shown.contains("<redacted>"));
}
use super::*;
use std::collections::HashMap;
fn env(pairs: &[(&str, &str)]) -> Result<Mailer, MailError> {
let m: HashMap<String, String> = pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Mailer::from_lookup(|k| m.get(k).cloned())
}
#[tokio::test]
async fn log_driver_sends() {
let m = env(&[]).unwrap();
m.send(
Mail::new()
.to("a@example.com")
.subject("hi")
.text("t")
.html("<b>t</b>"),
)
.await
.unwrap();
}
#[cfg(feature = "mail-templates")]
mod templates {
use crate::mail::{Mail, MailError, Template};
#[derive(Template)]
#[template(source = "<a href=\"{{ url }}\">{{ name }}</a>", ext = "html", askama = crate::mail::askama)]
struct Html<'a> {
name: &'a str,
url: &'a str,
}
#[derive(Template)]
#[template(source = "{{ name }}: {{ url }}", ext = "txt", askama = crate::mail::askama)]
struct Text<'a> {
name: &'a str,
url: &'a str,
}
struct Broken;
impl std::fmt::Display for Broken {
fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Err(std::fmt::Error)
}
}
#[derive(Template)]
#[template(source = "x{{ b }}", ext = "txt", askama = crate::mail::askama)]
struct Failing {
b: Broken,
}
#[test]
fn html_escapes_and_text_does_not() {
let (name, url) = ("<b>A</b> & \"q\" 'x'", "https://x.test/?a=1&b=2");
let m = Mail::new()
.text_template(&Text { name, url })
.unwrap()
.html_template(&Html { name, url })
.unwrap();
assert_eq!(
m.text.as_deref(),
Some("<b>A</b> & \"q\" 'x': https://x.test/?a=1&b=2")
);
let html = m.html.unwrap();
assert!(!html.contains("<b>") && !html.contains("&b=2"), "{html}");
assert!(
html.contains("<b>A</b> & "q" 'x'"),
"{html}"
);
assert!(
html.contains("href=\"https://x.test/?a=1&b=2\""),
"{html}"
);
}
#[test]
fn render_failure_is_a_mail_error_not_a_panic() {
let e = Mail::new()
.text_template(&Failing { b: Broken })
.unwrap_err();
assert!(matches!(e, MailError::Template(_)), "{e}");
}
}
#[test]
fn plaintext_smtp_is_for_loopback_hosts_only() {
for h in ["localhost", "LOCALHOST", "127.0.0.1", "127.9.9.9", "::1"] {
assert!(is_loopback_host(h), "{h}");
}
for h in [
"smtp.example.com",
"10.0.0.5",
"192.168.1.2",
"0.0.0.0",
"localhost.evil.com",
"",
] {
assert!(!is_loopback_host(h), "{h}");
}
}
#[tokio::test]
async fn invalid_address_errors() {
let m = Mailer::log("noreply@example.com");
let e = m
.send(Mail::new().to("not-an-address").subject("x").text("y"))
.await;
assert!(matches!(e, Err(MailError::Address(_))));
assert!(m.send(Mail::new().subject("x")).await.is_err());
}
#[test]
fn builder_fields_and_serde() {
let m = Mail::new()
.from("f@x.io")
.to("a@x.io")
.cc("c@x.io")
.bcc("b@x.io")
.subject("s")
.text("t")
.html("h");
assert_eq!((m.to.len(), m.cc.len(), m.bcc.len()), (1, 1, 1));
assert_eq!(
(m.subject.as_str(), m.text.as_deref(), m.html.as_deref()),
("s", Some("t"), Some("h"))
);
let back: Mail = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap();
assert_eq!(back, m);
}
#[test]
fn env_parsing() {
assert_eq!(env(&[]).unwrap().driver, Driver::Log);
assert!(env(&[("MAIL_DRIVER", "bogus")]).is_err());
assert!(env(&[("MAIL_DRIVER", "smtp")]).is_err());
assert!(
env(&[
("MAIL_DRIVER", "smtp"),
("MAIL_HOST", "h.io"),
("MAIL_PORT", "x")
])
.is_err()
);
let m = env(&[
("MAIL_DRIVER", "smtp"),
("MAIL_HOST", "smtp.example.com"),
("MAIL_PORT", "465"),
("MAIL_USERNAME", "u"),
("MAIL_PASSWORD", "p"),
("MAIL_FROM", "me@example.com"),
])
.unwrap();
assert_eq!(
m.driver,
Driver::Smtp(SmtpConfig {
host: "smtp.example.com".into(),
port: 465,
username: Some("u".into()),
password: Some("p".into())
})
);
assert!(
env(&[
("MAIL_DRIVER", "smtp"),
("MAIL_HOST", "h.io"),
("MAIL_FROM", "bad")
])
.is_err()
);
}
}