//! Mail from the app: SMTP submission to the fleet's mail server as the //! mailbox `reminders@lannadesk.com` (phase 8). Every mail sent or failed //! is written to the notifications log, so the office sees what went out. use std::time::Duration; use anyhow::{Context, Result}; use lettre::message::Mailbox; use lettre::message::header::ContentType; use lettre::transport::smtp::authentication::Credentials; use lettre::transport::smtp::client::{Tls, TlsParameters}; use lettre::transport::smtp::extension::ClientId; use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor}; use serde::Serialize; use sqlx::PgPool; use crate::config::{MailConfig, MailSecurity}; /// The sender and the reply address parse as addresses. pub fn check_addresses(cfg: &MailConfig) -> Result<()> { cfg.from .parse::() .with_context(|| format!("VISA_MAIL_FROM is not an address: {}", cfg.from))?; if let Some(r) = &cfg.reply_to { r.parse::() .with_context(|| format!("VISA_MAIL_REPLY_TO is not an address: {r}"))?; } Ok(()) } /// Whether a recipient's address is one mail can go to. pub fn valid_address(addr: &str) -> bool { let a = addr.trim(); a.len() <= 254 && a.parse::().is_ok() && a.contains('@') && !a.contains('<') } /// The name this machine gives the mail server: the app's public host. pub fn hello_name(public_url: &str) -> String { public_url .split("://") .nth(1) .unwrap_or("localhost") .split(['/', ':']) .next() .filter(|h| !h.is_empty()) .unwrap_or("localhost") .to_string() } /// A plain-text mail. pub struct Outgoing<'a> { pub to: &'a str, pub subject: &'a str, pub text: &'a str, } /// Sends one mail; Ok holds the server's answer ("2.0.0 Ok: queued as …"). /// `hello` names this machine to the server: the app's public name. pub async fn send(cfg: &MailConfig, hello: &str, mail: &Outgoing<'_>) -> Result { let mut builder = Message::builder() .from(cfg.from.parse()?) .to(mail.to.trim().parse().context("not an email address")?) .subject(mail.subject) .header(ContentType::TEXT_PLAIN); if let Some(r) = &cfg.reply_to { builder = builder.reply_to(r.parse()?); } let message = builder.body(mail.text.to_string())?; let tls = || TlsParameters::new(cfg.host.clone()); let mut transport = AsyncSmtpTransport::::builder_dangerous(&cfg.host) .port(cfg.port) .hello_name(ClientId::Domain(hello.to_string())) .timeout(Some(Duration::from_secs(20))) .tls(match cfg.security { MailSecurity::Tls => Tls::Wrapper(tls()?), MailSecurity::StartTls => Tls::Required(tls()?), MailSecurity::None => Tls::None, }); if let Some(p) = &cfg.password { transport = transport.credentials(Credentials::new(cfg.user.clone(), p.clone())); } let answer = transport .build() .send(message) .await .with_context(|| format!("sending through {}:{}", cfg.host, cfg.port))?; Ok(answer.message().collect::>().join(" ")) } /// One line of the notifications log. #[derive(Clone, Debug, sqlx::FromRow, Serialize)] pub struct Logged { pub id: i64, pub channel: String, pub purpose: String, pub recipient: String, pub subject: String, pub status: String, pub detail: String, pub actor: String, pub created_at: chrono::DateTime, } /// What a notification was and how it went, for the log. pub struct Entry<'a> { pub channel: &'a str, pub purpose: &'a str, pub recipient: &'a str, pub subject: &'a str, pub result: &'a Result, pub actor: &'a str, } pub async fn log(db: &PgPool, e: &Entry<'_>) -> Result { let (status, detail) = match e.result { Ok(answer) => ("sent", answer.clone()), Err(err) => ("failed", format!("{err:#}")), }; let detail: String = detail.chars().take(1000).collect(); Ok(sqlx::query_scalar( "INSERT INTO notifications (channel, purpose, recipient, subject, status, detail, actor) \ VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id", ) .bind(e.channel) .bind(e.purpose) .bind(e.recipient.trim()) .bind(e.subject) .bind(status) .bind(detail) .bind(e.actor) .fetch_one(db) .await?) } pub async fn recent(db: &PgPool, limit: i64) -> Result> { Ok( sqlx::query_as("SELECT * FROM notifications ORDER BY id DESC LIMIT $1") .bind(limit) .fetch_all(db) .await?, ) } pub async fn get(db: &PgPool, id: i64) -> Result> { Ok(sqlx::query_as("SELECT * FROM notifications WHERE id = $1") .bind(id) .fetch_optional(db) .await?) } /// The address someone last sent a test to, to offer it again. pub async fn last_test_address(db: &PgPool, actor: &str) -> Result> { Ok(sqlx::query_scalar( "SELECT recipient FROM notifications WHERE actor = $1 AND channel = 'email' \ AND purpose = 'test' ORDER BY id DESC LIMIT 1", ) .bind(actor) .fetch_optional(db) .await?) } #[cfg(test)] mod tests { use super::*; #[test] fn addresses_are_checked() { assert!(valid_address("alex@buildfor.life")); assert!(valid_address(" contact@lannadesk.com ")); assert!(!valid_address("alex")); assert!( !valid_address("Alex "), "the address only" ); assert!(!valid_address("a@b@c")); } #[test] fn the_server_hears_the_public_name() { assert_eq!(hello_name("https://app.lannadesk.com"), "app.lannadesk.com"); assert_eq!(hello_name("http://127.0.0.1:8040"), "127.0.0.1"); assert_eq!(hello_name("nonsense"), "localhost"); } }