Skip to main content

quokka_mailing/
lib.rs

1pub mod error;
2
3pub use error::*;
4pub use mail_send::mail_builder::MessageBuilder;
5
6use quokka_config::{Config, TryFromConfig};
7
8///
9/// Sends maills.
10///
11/// Everyone has to send mails, no matter if we love it or hate it
12///
13/// # Example
14///
15/// Use it in your axum handler, or wherever else you like to send mails from.
16///
17/// ```no_run
18/// use quokka_mailing::Mailing;
19/// use mail_send::mail_builder::MessageBuilder;
20///
21/// async {
22/// let mailer = Mailing::default();
23///
24/// mailer.send_mail(MessageBuilder::new()
25///     .from(mailer.sender())
26///     .to(vec![("Localhost", "mailhog@localhost")])
27///     .subject("Hello")
28///     .html_body("<h1>Hello Mailhog</h1>")
29///     .text_body("Hello Mailhog (without html)"))
30///     .await.ok();
31/// };
32/// ```
33///
34#[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    /// Builds the Mailing module from a [Module](crate::config::Module) configuration item.
146    /// It requires the values outlined in the [MailingConfig] struct.
147    /// Requires the module name to be "mailer".
148    ///
149    /// ```rust
150    /// use quokka_mailing::Mailing;
151    /// use quokka_config::{Module, Config, TryFromConfig};
152    ///
153    /// #[tokio::main]
154    /// async fn main() {
155    /// let module = Module {
156    ///     module: "mailer".to_string(),
157    ///     config: toml::Value::Table(toml::toml! {
158    ///         host = "test-mailer.fail"
159    ///         port = 1025
160    ///         ssl_mode = "plain"
161    ///         from_name = "My Website"
162    ///         from_email = "my-website@localhost"
163    ///         credentials = { plain = { username = "some_user", password = "secret_password" } }
164    ///    }),
165    /// };
166    ///
167    /// assert!(Mailing::try_from_config(&Config { modules: vec![module] }).await.is_ok());
168    ///
169    /// let module = Module {
170    ///     module: "not_mailer".to_string(),
171    ///     config: toml::Value::String(String::new())
172    /// };
173    ///
174    /// assert!(Mailing::try_from_config(&Config { modules: vec![module] }).await.is_err()); // Return [Option::None] as the module is not responsible for the mailer configuration
175    ///
176    /// let module = Module {
177    ///     module: "mailer".to_string(),
178    ///     config: toml::Value::String(String::new())
179    /// };
180    ///
181    /// assert!(Mailing::try_from_config(&Config { modules: vec![module] }).await.is_err()); // Failes because the configuration format does not match
182    /// }
183    /// ```
184    ///
185    #[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}