2025-02-26 13:10:43 -08:00
|
|
|
use anyhow::{Context, Result};
|
|
|
|
use axum::extract::FromRef;
|
|
|
|
use lettre::{AsyncSmtpTransport, AsyncTransport, Tokio1Executor};
|
|
|
|
use serde::{Serialize, Serializer};
|
|
|
|
|
|
|
|
use crate::app_state::AppState;
|
|
|
|
|
|
|
|
const POSTMARK_EMAIL_BATCH_URL: &'static str = "https://api.postmarkapp.com/email/batch";
|
|
|
|
|
2025-03-08 22:18:24 -08:00
|
|
|
#[derive(Clone, Serialize)]
|
2025-02-26 13:10:43 -08:00
|
|
|
pub struct Message {
|
|
|
|
#[serde(rename = "From")]
|
|
|
|
pub from: lettre::message::Mailbox,
|
|
|
|
#[serde(rename = "To")]
|
|
|
|
#[serde(serialize_with = "serialize_mailboxes")]
|
|
|
|
pub to: lettre::message::Mailboxes,
|
|
|
|
#[serde(rename = "Subject")]
|
|
|
|
pub subject: String,
|
|
|
|
#[serde(rename = "TextBody")]
|
|
|
|
pub text_body: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub trait MailSender: Clone + Sync {
|
2025-03-08 22:18:24 -08:00
|
|
|
// TODO: Document a consistent contract for how partial successes should
|
|
|
|
// behave
|
2025-02-26 13:10:43 -08:00
|
|
|
async fn send_batch(&self, emails: Vec<Message>) -> Result<(), anyhow::Error>;
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
pub enum Mailer {
|
|
|
|
Smtp(SmtpSender),
|
|
|
|
Postmark(PostmarkSender),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Mailer {
|
|
|
|
pub fn new_smtp(opts: SmtpOptions) -> Result<Self> {
|
|
|
|
Ok(Self::Smtp(SmtpSender::new(opts)?))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn new_postmark(server_token: String) -> Result<Self> {
|
|
|
|
Ok(Self::Postmark(PostmarkSender::new(server_token)?))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn with_reqwest_client(self, client: reqwest::Client) -> Self {
|
|
|
|
match self {
|
|
|
|
Self::Postmark(sender) => Self::Postmark(sender.with_reqwest_client(client)),
|
|
|
|
_ => self,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl MailSender for Mailer {
|
|
|
|
async fn send_batch(&self, emails: Vec<Message>) -> Result<(), anyhow::Error> {
|
|
|
|
match self {
|
|
|
|
Mailer::Smtp(sender) => sender.send_batch(emails).await,
|
|
|
|
Mailer::Postmark(sender) => sender.send_batch(emails).await,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
struct SmtpSender {
|
|
|
|
transport: AsyncSmtpTransport<Tokio1Executor>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct SmtpOptions {
|
|
|
|
pub server: String,
|
|
|
|
pub username: String,
|
|
|
|
pub password: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SmtpSender {
|
|
|
|
fn new(opts: SmtpOptions) -> Result<Self> {
|
|
|
|
let mailer_creds =
|
|
|
|
lettre::transport::smtp::authentication::Credentials::new(opts.username, opts.password);
|
|
|
|
let transport = lettre::AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&opts.server)
|
|
|
|
.context("unable to initialize starttls_relay")?
|
|
|
|
.credentials(mailer_creds)
|
|
|
|
.build();
|
|
|
|
Ok(Self { transport })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TryInto<lettre::Message> for Message {
|
|
|
|
type Error = anyhow::Error;
|
|
|
|
|
|
|
|
fn try_into(self) -> Result<lettre::Message, Self::Error> {
|
|
|
|
let mut builder = lettre::Message::builder()
|
|
|
|
.from(self.from.clone())
|
|
|
|
.subject(self.subject)
|
|
|
|
.header(lettre::message::header::ContentType::TEXT_PLAIN);
|
|
|
|
for to_addr in self.to {
|
|
|
|
builder = builder.to(to_addr);
|
|
|
|
}
|
|
|
|
let message = builder.body(self.text_body)?;
|
|
|
|
Ok(message)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn serialize_mailboxes<S>(t: &lettre::message::Mailboxes, s: S) -> Result<S::Ok, S::Error>
|
|
|
|
where
|
|
|
|
S: Serializer,
|
|
|
|
{
|
|
|
|
Ok(s.serialize_str(&t.to_string())?)
|
|
|
|
}
|
|
|
|
|
|
|
|
impl MailSender for SmtpSender {
|
|
|
|
async fn send_batch(&self, emails: Vec<Message>) -> Result<()> {
|
|
|
|
for email in emails {
|
|
|
|
self.transport.send(email.try_into()?).await?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
struct PostmarkSender {
|
|
|
|
client: reqwest::Client,
|
|
|
|
server_token: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PostmarkSender {
|
|
|
|
fn new(server_token: String) -> Result<Self> {
|
|
|
|
Ok(Self {
|
|
|
|
client: reqwest::ClientBuilder::new().https_only(true).build()?,
|
|
|
|
server_token,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn with_reqwest_client(self, client: reqwest::Client) -> Self {
|
|
|
|
Self { client, ..self }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl MailSender for PostmarkSender {
|
2025-03-08 22:18:24 -08:00
|
|
|
async fn send_batch(&self, mut emails: Vec<Message>) -> Result<()> {
|
|
|
|
// https://postmarkapp.com/support/article/1056-what-are-the-attachment-and-email-size-limits
|
|
|
|
const POSTMARK_MAX_BATCH_ENTRIES: usize = 500;
|
|
|
|
const POSTMARK_MAX_REQUEST_BYTES: usize = 50 * 1000 * 1000;
|
|
|
|
// TODO: Check email subject and body size against Postmark limits
|
|
|
|
let count = emails.len();
|
|
|
|
|
|
|
|
// TODO: This may be more readable as a closure
|
|
|
|
/**
|
|
|
|
* Recursively splits the email batch in half and tries to send each
|
|
|
|
* half independently, allowing both to run to completion and then
|
|
|
|
* returning the first error of the two results, if present. Panics if
|
|
|
|
* the batch is too small to split, so the caller is responsible for
|
|
|
|
* handling that case before invoking the macro.
|
|
|
|
*/
|
|
|
|
macro_rules! split_and_retry {
|
|
|
|
() => {
|
|
|
|
tracing::debug!("retrying Postmark send with smaller batches");
|
|
|
|
assert!(count > 1);
|
|
|
|
let res1 = Box::pin(self.send_batch(emails.split_off(count / 2))).await;
|
|
|
|
let res2 = Box::pin(self.send_batch(emails)).await;
|
|
|
|
match (res1, res2) {
|
|
|
|
(Err(err), _) => {
|
|
|
|
return Err(err);
|
|
|
|
}
|
|
|
|
(_, Err(err)) => {
|
|
|
|
return Err(err);
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
if count == 0 {
|
|
|
|
tracing::debug!("no Postmark messages to send");
|
|
|
|
Ok(())
|
|
|
|
} else if count > POSTMARK_MAX_BATCH_ENTRIES {
|
|
|
|
split_and_retry!();
|
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
let body = serde_json::to_string(&emails)?;
|
|
|
|
if body.len() > POSTMARK_MAX_REQUEST_BYTES {
|
|
|
|
if count > 1 {
|
|
|
|
split_and_retry!();
|
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
Err(anyhow::anyhow!(
|
|
|
|
"Postmark requests may not exceed {} bytes",
|
|
|
|
POSTMARK_MAX_REQUEST_BYTES
|
|
|
|
))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
tracing::debug!("sending Postmark batch of {} messages", count);
|
|
|
|
let resp = self
|
|
|
|
.client
|
|
|
|
.post(POSTMARK_EMAIL_BATCH_URL)
|
|
|
|
.header("X-Postmark-Server-Token", &self.server_token)
|
|
|
|
.header(reqwest::header::CONTENT_TYPE, "application/json")
|
|
|
|
.body(body)
|
|
|
|
.send()
|
|
|
|
.await?;
|
|
|
|
if resp.status().is_client_error() && count > 1 {
|
|
|
|
split_and_retry!();
|
|
|
|
}
|
|
|
|
resp.error_for_status()?;
|
|
|
|
tracing::debug!("sent Postmark batch of {} messages", count);
|
|
|
|
Ok(())
|
|
|
|
}
|
2025-02-26 13:10:43 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromRef<AppState> for Mailer {
|
|
|
|
fn from_ref(state: &AppState) -> Mailer {
|
|
|
|
state.mailer.clone()
|
|
|
|
}
|
|
|
|
}
|