mail-list 0.2.6-alpha

Email subscriptions list library. Unicast, narrowcast and broadcast lists
Documentation
use std::borrow::Cow;

use lettre::{AsyncSmtpTransport, AsyncTransport, Message, transport::smtp::response::Severity};

use crate::{EmailEnvelopeDetails, MailListError, MailListResult};

#[derive(Debug)]
pub struct Smtps {
    pub(crate) domain: Cow<'static, str>,
    pub(crate) ehlo_name: Option<Cow<'static, str>>,
    #[cfg(feature = "tokio-runtime")]
    pub(crate) mailer: AsyncSmtpTransport<lettre::Tokio1Executor>,
}

impl Smtps {
    pub fn domain(&self) -> &str {
        self.domain.as_ref()
    }

    pub fn ehlo_name(&self) -> Option<&Cow<'_, str>> {
        self.ehlo_name.as_ref()
    }

    #[cfg(feature = "tokio-runtime")]
    pub fn mailer(&self) -> &AsyncSmtpTransport<lettre::Tokio1Executor> {
        &self.mailer
    }

    pub async fn send(&self, message: &EmailEnvelopeDetails) -> MailListResult<()> {
        let email = Message::builder()
            .from(message.from_as_mailbox())
            .reply_to(message.reply_as_mailbox())
            .to(message.to_as_mailbox())
            .subject(message.subject.as_str())
            .header(lettre::message::header::ContentType::TEXT_HTML)
            .body(message.body.to_string())
            .map_err(|error| MailListError::Mailer(error.to_string()))?;

        let response = self
            .mailer
            .send(email)
            .await
            .map_err(|error| MailListError::MailDelivery(error.to_string()))?;

        if response.code().severity == Severity::PositiveCompletion {
            Ok(())
        } else {
            Err(MailListError::Smtps(
                response.message().map(|msg| msg.to_string()).collect(),
            ))
        }
    }

    pub async fn test_connection(&self) -> MailListResult<bool> {
        self.mailer
            .test_connection()
            .await
            .map_err(|error| MailListError::Mailer(error.to_string()))
    }
}