quokka-mailing 0.3.0-beta.0

A new framework for building old-school fullstack web applications
Documentation
pub mod error;

pub use error::*;
pub use mail_send::mail_builder::MessageBuilder;

use quokka_config::{Config, TryFromConfig};

///
/// Sends maills.
///
/// Everyone has to send mails, no matter if we love it or hate it
///
/// # Example
///
/// Use it in your axum handler, or wherever else you like to send mails from.
///
/// ```no_run
/// use quokka_mailing::Mailing;
/// use mail_send::mail_builder::MessageBuilder;
///
/// async {
/// let mailer = Mailing::default();
///
/// mailer.send_mail(MessageBuilder::new()
///     .from(mailer.sender())
///     .to(vec![("Localhost", "mailhog@localhost")])
///     .subject("Hello")
///     .html_body("<h1>Hello Mailhog</h1>")
///     .text_body("Hello Mailhog (without html)"))
///     .await.ok();
/// };
/// ```
///
#[derive(Clone)]
pub struct Mailing {
    pub from_name: String,
    pub from_email: String,
    use_ssl: bool,
    builder: mail_send::SmtpClientBuilder<String>,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MailingConfig {
    host: String,
    port: u16,
    credentials: Option<MailingCredentials>,
    ssl_mode: SslMode,
    from_name: String,
    from_email: String,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MailingCredentials {
    Plain { username: String, password: String },
    XOauth2 { username: String, secret: String },
    OAuthBearer { token: String },
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SslMode {
    Plain,
    Strict,
}

impl Mailing {
    pub fn with_config(config: &MailingConfig) -> Self {
        let mut builder = mail_send::SmtpClientBuilder::new(config.host.to_string(), config.port);

        if let Some(credentials) = &config.credentials {
            builder = builder.credentials(credentials);
        }

        if matches!(config.ssl_mode, SslMode::Strict) {
            builder = builder.implicit_tls(true);
        }

        if matches!(config.ssl_mode, SslMode::Plain) {
            builder = builder.implicit_tls(false);
        }

        Self {
            builder,
            use_ssl: matches!(config.ssl_mode, SslMode::Strict),
            from_name: config.from_name.to_string(),
            from_email: config.from_email.to_string(),
        }
    }

    pub async fn send_mail(
        &self,
        message: impl mail_send::smtp::message::IntoMessage<'_>,
    ) -> crate::Result<()> {
        let addr = self.builder.addr.to_string();
        let message = message
            .into_message()
            .inspect_err(|error| tracing::error!(?error, "Unable to compile message"))
            .map_err(|_| Error::CompileMessageError)?;
        let recipients = message
            .rcpt_to
            .iter()
            .map(|rcpt| rcpt.email.to_string())
            .collect::<Vec<_>>();

        if self.use_ssl {
            self.builder
                .clone()
                .connect()
                .await
                .inspect_err(|error| {
                    tracing::error!(?error, ?addr, "Unable to connect to Mail Server")
                })
                .map_err(|_| crate::Error::ConnectToMailserverError(addr))?
                .send(message)
                .await
                .inspect_err(|error| tracing::error!(?error, ?recipients, "Unable to send E-Mail"))
                .map_err(|_| crate::Error::UnableToSendMessage(recipients))?;
        } else {
            self.builder
                .clone()
                .connect_plain()
                .await
                .inspect_err(|error| {
                    tracing::error!(?error, ?addr, "Unable to connect to Mail Server")
                })
                .map_err(|_| crate::Error::ConnectToMailserverError(addr))?
                .send(message)
                .await
                .inspect_err(|error| tracing::error!(?error, ?recipients, "Unable to send E-Mail"))
                .map_err(|_| crate::Error::UnableToSendMessage(recipients))?;
        };

        Ok(())
    }

    pub fn sender(&self) -> (String, String) {
        (self.from_name.clone(), self.from_email.clone())
    }
}

impl TryFromConfig for Mailing {
    type Error = crate::Error;

    /// Builds the Mailing module from a [Module](crate::config::Module) configuration item.
    /// It requires the values outlined in the [MailingConfig] struct.
    /// Requires the module name to be "mailer".
    ///
    /// ```rust
    /// use quokka_mailing::Mailing;
    /// use quokka_config::{Module, Config, TryFromConfig};
    ///
    /// #[tokio::main]
    /// async fn main() {
    /// let module = Module {
    ///     module: "mailer".to_string(),
    ///     config: toml::Value::Table(toml::toml! {
    ///         host = "test-mailer.fail"
    ///         port = 1025
    ///         ssl_mode = "plain"
    ///         from_name = "My Website"
    ///         from_email = "my-website@localhost"
    ///         credentials = { plain = { username = "some_user", password = "secret_password" } }
    ///    }),
    /// };
    ///
    /// assert!(Mailing::try_from_config(&Config { modules: vec![module] }).await.is_ok());
    ///
    /// let module = Module {
    ///     module: "not_mailer".to_string(),
    ///     config: toml::Value::String(String::new())
    /// };
    ///
    /// 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
    ///
    /// let module = Module {
    ///     module: "mailer".to_string(),
    ///     config: toml::Value::String(String::new())
    /// };
    ///
    /// assert!(Mailing::try_from_config(&Config { modules: vec![module] }).await.is_err()); // Failes because the configuration format does not match
    /// }
    /// ```
    ///
    #[tracing::instrument]
    async fn try_from_config(config: &Config) -> crate::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self::with_config(&config.get_module("mailer")?))
    }
}

impl From<&MailingCredentials> for mail_send::Credentials<String> {
    fn from(val: &MailingCredentials) -> Self {
        match val {
            MailingCredentials::Plain { username, password } => {
                mail_send::Credentials::new(username.to_string(), password.to_string())
            }
            MailingCredentials::XOauth2 { username, secret } => {
                mail_send::Credentials::new_xoauth2(username.to_string(), secret.to_string())
            }
            MailingCredentials::OAuthBearer { token } => {
                mail_send::Credentials::new_oauth_from_token(token)
            }
        }
    }
}

impl std::fmt::Debug for Mailing {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "Mailing {{ use_ssl: {}, from_name: {}, from_email: {} .. }}",
            self.use_ssl, self.from_name, self.from_email,
        ))
    }
}

impl Default for Mailing {
    fn default() -> Self {
        Self {
            from_name: "Quokka Mailing".to_string(),
            from_email: "quokka@localhost".to_string(),
            use_ssl: false,
            builder: mail_send::SmtpClientBuilder::new("localhost".to_string(), 25),
        }
    }
}