aurelin_framework/
mail.rs1use std::{collections::HashMap, fmt, num::ParseIntError};
2
3use crate::events::{DispatchError, DispatchOutcome, EventDispatcher};
4use lettre::{
5 AsyncSmtpTransport, AsyncTransport, Tokio1Executor,
6 address::AddressError,
7 error::Error as LettreError,
8 message::Mailbox,
9 transport::smtp::{Error as SmtpError, authentication::Credentials},
10};
11use thiserror::Error;
12
13mod message;
14pub use message::MailMessage;
15
16pub struct MessageSending(pub MailMessage);
19
20pub struct MessageSent(pub MailMessage);
22
23pub struct MessageFailed(pub MailMessage);
25
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28pub enum SendOutcome {
29 Sent,
31 Cancelled,
33}
34
35#[derive(Clone)]
36pub struct Mailer {
37 transport: Option<AsyncSmtpTransport<Tokio1Executor>>,
38 from: Option<Mailbox>,
39 events: Option<EventDispatcher>,
40}
41
42impl fmt::Debug for Mailer {
43 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
44 formatter.debug_struct("Mailer").field("smtp", &self.transport.is_some()).finish_non_exhaustive()
45 }
46}
47
48impl Mailer {
49 pub fn log() -> Self {
50 Self { transport: None, from: None, events: None }
51 }
52
53 pub fn with_events(mut self, events: EventDispatcher) -> Self {
55 self.events = Some(events);
56 self
57 }
58
59 pub fn from_environment(environment: &HashMap<String, String>) -> Result<Self, MailError> {
60 match environment.get("MAIL_MAILER").map_or("log", String::as_str) {
61 "log" => {
62 let from = environment
63 .get("MAIL_FROM_ADDRESS")
64 .filter(|value| !value.is_empty())
65 .map(|address| {
66 address.parse().map(|address| Mailbox::new(environment.get("MAIL_FROM_NAME").cloned(), address))
67 })
68 .transpose()?;
69 Ok(Self { transport: None, from, events: None })
70 }
71 "smtp" => Self::smtp(environment),
72 mailer => Err(MailError::UnsupportedMailer(mailer.to_owned())),
73 }
74 }
75
76 pub async fn send(&self, message: MailMessage) -> Result<(), MailError> {
77 self.send_with_outcome(message).await.map(|_| ())
78 }
79
80 pub async fn send_with_outcome(&self, message: MailMessage) -> Result<SendOutcome, MailError> {
82 let from = match (&self.from, &self.transport) {
83 (None, None) => Some(Mailbox::new(None, "hello@example.com".parse()?)),
84 _ => self.from.clone(),
85 };
86 let built = match message.clone().build(from) {
87 Ok(built) => built,
88 Err(error) => {
89 self.failed(message).await?;
90 return Err(error);
91 }
92 };
93 if let Some(events) = &self.events {
94 if events.dispatch(MessageSending(message.clone())).await? == DispatchOutcome::Stopped {
95 return Ok(SendOutcome::Cancelled);
96 }
97 }
98 if let Some(transport) = &self.transport {
99 if let Err(error) = transport.send(built).await {
100 self.failed(message).await?;
101 return Err(error.into());
102 }
103 } else {
104 tracing::info!(message = %String::from_utf8_lossy(&built.formatted()), "mail notification");
105 }
106 if let Some(events) = &self.events {
107 events.dispatch(MessageSent(message)).await?;
108 }
109 Ok(SendOutcome::Sent)
110 }
111
112 async fn failed(&self, message: MailMessage) -> Result<(), MailError> {
113 if let Some(events) = &self.events {
114 events.dispatch(MessageFailed(message)).await?;
115 }
116 Ok(())
117 }
118
119 fn smtp(environment: &HashMap<String, String>) -> Result<Self, MailError> {
120 let host = required(environment, "MAIL_HOST")?;
121 let encryption = environment.get("MAIL_ENCRYPTION").map_or("tls", String::as_str);
122 let mut builder = match encryption {
123 "tls" => AsyncSmtpTransport::<Tokio1Executor>::relay(host)?,
124 "starttls" => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(host)?,
125 "none" => AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(host),
126 value => return Err(MailError::UnsupportedEncryption(value.to_owned())),
127 };
128 if let Some(port) = environment.get("MAIL_PORT").filter(|value| !value.is_empty()) {
129 builder = builder.port(port.parse()?);
130 }
131 match (
132 environment.get("MAIL_USERNAME").filter(|value| !value.is_empty()),
133 environment.get("MAIL_PASSWORD").filter(|value| !value.is_empty()),
134 ) {
135 (Some(username), Some(password)) => {
136 builder = builder.credentials(Credentials::new(username.clone(), password.clone()));
137 }
138 (None, None) => {}
139 _ => return Err(MailError::IncompleteCredentials),
140 }
141 let address = required(environment, "MAIL_FROM_ADDRESS")?.parse()?;
142 let from = Mailbox::new(environment.get("MAIL_FROM_NAME").cloned(), address);
143 Ok(Self { transport: Some(builder.build()), from: Some(from), events: None })
144 }
145}
146
147fn required<'a>(environment: &'a HashMap<String, String>, name: &'static str) -> Result<&'a str, MailError> {
148 environment.get(name).filter(|value| !value.is_empty()).map(String::as_str).ok_or(MailError::Missing(name))
149}
150
151#[derive(Debug, Error)]
152pub enum MailError {
153 #[error("{0} must be set for the configured mailer")]
154 Missing(&'static str),
155 #[error("unsupported mailer: {0}")]
156 UnsupportedMailer(String),
157 #[error("unsupported mail encryption: {0}")]
158 UnsupportedEncryption(String),
159 #[error("MAIL_USERNAME and MAIL_PASSWORD must either both be set or both be omitted")]
160 IncompleteCredentials,
161 #[error("invalid mail port")]
162 Port(#[from] ParseIntError),
163 #[error("invalid mail address")]
164 Address(#[from] AddressError),
165 #[error("could not build the mail message")]
166 Message(#[from] LettreError),
167 #[error("SMTP delivery failed")]
168 Delivery(#[from] SmtpError),
169 #[error(transparent)]
171 Event(#[from] DispatchError),
172}