1pub mod error;
2
3pub use error::*;
4pub use mail_send::mail_builder::MessageBuilder;
5
6use quokka_config::{Config, TryFromConfig};
7
8#[derive(Clone)]
35pub struct Mailing {
36 pub from_name: String,
37 pub from_email: String,
38 use_ssl: bool,
39 builder: mail_send::SmtpClientBuilder<String>,
40}
41
42#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
43pub struct MailingConfig {
44 host: String,
45 port: u16,
46 credentials: Option<MailingCredentials>,
47 ssl_mode: SslMode,
48 from_name: String,
49 from_email: String,
50}
51
52#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
53#[serde(rename_all = "snake_case")]
54pub enum MailingCredentials {
55 Plain { username: String, password: String },
56 XOauth2 { username: String, secret: String },
57 OAuthBearer { token: String },
58}
59
60#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
61#[serde(rename_all = "snake_case")]
62pub enum SslMode {
63 Plain,
64 Strict,
65}
66
67impl Mailing {
68 pub fn with_config(config: &MailingConfig) -> Self {
69 let mut builder = mail_send::SmtpClientBuilder::new(config.host.to_string(), config.port);
70
71 if let Some(credentials) = &config.credentials {
72 builder = builder.credentials(credentials);
73 }
74
75 if matches!(config.ssl_mode, SslMode::Strict) {
76 builder = builder.implicit_tls(true);
77 }
78
79 if matches!(config.ssl_mode, SslMode::Plain) {
80 builder = builder.implicit_tls(false);
81 }
82
83 Self {
84 builder,
85 use_ssl: matches!(config.ssl_mode, SslMode::Strict),
86 from_name: config.from_name.to_string(),
87 from_email: config.from_email.to_string(),
88 }
89 }
90
91 pub async fn send_mail(
92 &self,
93 message: impl mail_send::smtp::message::IntoMessage<'_>,
94 ) -> crate::Result<()> {
95 let addr = self.builder.addr.to_string();
96 let message = message
97 .into_message()
98 .inspect_err(|error| tracing::error!(?error, "Unable to compile message"))
99 .map_err(|_| Error::CompileMessageError)?;
100 let recipients = message
101 .rcpt_to
102 .iter()
103 .map(|rcpt| rcpt.email.to_string())
104 .collect::<Vec<_>>();
105
106 if self.use_ssl {
107 self.builder
108 .clone()
109 .connect()
110 .await
111 .inspect_err(|error| {
112 tracing::error!(?error, ?addr, "Unable to connect to Mail Server")
113 })
114 .map_err(|_| crate::Error::ConnectToMailserverError(addr))?
115 .send(message)
116 .await
117 .inspect_err(|error| tracing::error!(?error, ?recipients, "Unable to send E-Mail"))
118 .map_err(|_| crate::Error::UnableToSendMessage(recipients))?;
119 } else {
120 self.builder
121 .clone()
122 .connect_plain()
123 .await
124 .inspect_err(|error| {
125 tracing::error!(?error, ?addr, "Unable to connect to Mail Server")
126 })
127 .map_err(|_| crate::Error::ConnectToMailserverError(addr))?
128 .send(message)
129 .await
130 .inspect_err(|error| tracing::error!(?error, ?recipients, "Unable to send E-Mail"))
131 .map_err(|_| crate::Error::UnableToSendMessage(recipients))?;
132 };
133
134 Ok(())
135 }
136
137 pub fn sender(&self) -> (String, String) {
138 (self.from_name.clone(), self.from_email.clone())
139 }
140}
141
142impl TryFromConfig for Mailing {
143 type Error = crate::Error;
144
145 #[tracing::instrument]
186 async fn try_from_config(config: &Config) -> crate::Result<Self>
187 where
188 Self: Sized,
189 {
190 Ok(Self::with_config(&config.get_module("mailer")?))
191 }
192}
193
194impl From<&MailingCredentials> for mail_send::Credentials<String> {
195 fn from(val: &MailingCredentials) -> Self {
196 match val {
197 MailingCredentials::Plain { username, password } => {
198 mail_send::Credentials::new(username.to_string(), password.to_string())
199 }
200 MailingCredentials::XOauth2 { username, secret } => {
201 mail_send::Credentials::new_xoauth2(username.to_string(), secret.to_string())
202 }
203 MailingCredentials::OAuthBearer { token } => {
204 mail_send::Credentials::new_oauth_from_token(token)
205 }
206 }
207 }
208}
209
210impl std::fmt::Debug for Mailing {
211 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212 f.write_fmt(format_args!(
213 "Mailing {{ use_ssl: {}, from_name: {}, from_email: {} .. }}",
214 self.use_ssl, self.from_name, self.from_email,
215 ))
216 }
217}
218
219impl Default for Mailing {
220 fn default() -> Self {
221 Self {
222 from_name: "Quokka Mailing".to_string(),
223 from_email: "quokka@localhost".to_string(),
224 use_ssl: false,
225 builder: mail_send::SmtpClientBuilder::new("localhost".to_string(), 25),
226 }
227 }
228}