mailman 0.2.0

SDK for mailman, a microservice that sends emails on your behalf over SMTP.
Documentation
//! Rust client SDK for [mailman](https://github.com/bytebury/mailman), a
//! microservice that sends emails on your behalf over SMTP.
//!
//! Mailman ships as two things, mirroring
//! [geodude](https://github.com/bytebury/geodude):
//!
//! - an **HTTP microservice** that owns the SMTP credentials and sends mail, and
//! - a **Rust client crate** (this crate's default `client` feature) that other
//!   services use to ask it to send mail.
//!
//! # Quickstart
//!
//! Point at your mailman server once, then send mail from anywhere:
//!
//! ```no_run
//! # async fn run() -> Result<(), mailman::Error> {
//! mailman::setup("https://mailman.example.com", "super-secret-token")?;
//!
//! let email = mailman::SendEmailRequest::new(
//!     "Hello from mailman",
//!     "This one's plain text.",
//!     ["alice@example.com"],
//! );
//! mailman::send(&email).await?;
//! # Ok(()) }
//! ```
//!
//! Or read the URL and token from the environment (`MAILMAN_URL` and
//! `MAILMAN_API_TOKEN`):
//!
//! ```no_run
//! # async fn run() -> Result<(), mailman::Error> {
//! let email = mailman::SendEmailRequest::new(
//!     "Hello",
//!     "<h1>Hi!</h1>",
//!     ["bob@example.com"],
//! )
//! .html(true)
//! .cc(["carol@example.com"]);
//!
//! // `send` lazily falls back to MAILMAN_URL / MAILMAN_API_TOKEN on first
//! // call, so the env-only path can skip the init call entirely.
//! mailman::send(&email).await?;
//! # Ok(()) }
//! ```
//!
//! For multiple servers or finer control over the `reqwest::Client`, construct a
//! [`Client`] directly with [`Client::new`] or [`Client::with_http`].

use serde::{Deserialize, Serialize};

/// A request to send an email. This is the JSON body of `POST /send`.
///
/// Build one with [`SendEmailRequest::new`] and the chainable setters, or
/// construct the struct literal directly — every field is public.
///
/// `to` is required and may contain many recipients; `cc` and `attachments`
/// default to empty when omitted. Each address accepts either a bare email
/// (`alice@example.com`) or a named mailbox (`Alice <alice@example.com>`).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct SendEmailRequest {
    /// The email subject line.
    pub subject: String,
    /// The email body. Plain text by default; set `html` to `true` to send it
    /// as an HTML body instead.
    pub body: String,
    /// Recipients. At least one is required.
    pub to: Vec<String>,
    /// Carbon-copy recipients.
    #[serde(default)]
    pub cc: Vec<String>,
    /// File attachments.
    #[serde(default)]
    pub attachments: Vec<Attachment>,
    /// Optional override for the From address. Falls back to the server's
    /// `SMTP_FROM` when omitted.
    #[serde(default)]
    pub from: Option<String>,
    /// Treat `body` as HTML (`text/html`) instead of plain text.
    #[serde(default)]
    pub html: bool,
}

impl SendEmailRequest {
    /// Start a plain-text email to one or more recipients.
    ///
    /// ```
    /// let email = mailman::SendEmailRequest::new(
    ///     "Subject",
    ///     "Body text",
    ///     ["alice@example.com", "Bob <bob@example.com>"],
    /// );
    /// assert_eq!(email.to.len(), 2);
    /// ```
    pub fn new<S, B, T, I>(subject: S, body: B, to: I) -> Self
    where
        S: Into<String>,
        B: Into<String>,
        T: Into<String>,
        I: IntoIterator<Item = T>,
    {
        Self {
            subject: subject.into(),
            body: body.into(),
            to: to.into_iter().map(Into::into).collect(),
            ..Default::default()
        }
    }

    /// Set the carbon-copy recipients.
    pub fn cc<T, I>(mut self, cc: I) -> Self
    where
        T: Into<String>,
        I: IntoIterator<Item = T>,
    {
        self.cc = cc.into_iter().map(Into::into).collect();
        self
    }

    /// Override the From address for this message (otherwise the server's
    /// `SMTP_FROM` is used).
    pub fn from(mut self, from: impl Into<String>) -> Self {
        self.from = Some(from.into());
        self
    }

    /// Send `body` as `text/html` instead of plain text.
    pub fn html(mut self, html: bool) -> Self {
        self.html = html;
        self
    }

    /// Add a file attachment.
    pub fn attach(mut self, attachment: Attachment) -> Self {
        self.attachments.push(attachment);
        self
    }
}

/// A single file attachment. `content` is the file's bytes encoded as standard
/// (RFC 4648) base64.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct Attachment {
    /// The filename shown to the recipient, e.g. `invoice.pdf`.
    pub filename: String,
    /// The MIME type of the attachment, e.g. `application/pdf`.
    pub content_type: String,
    /// The attachment's bytes, base64-encoded.
    pub content: String,
}

impl Attachment {
    /// Build an attachment from already-base64-encoded `content`.
    pub fn new(
        filename: impl Into<String>,
        content_type: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        Self {
            filename: filename.into(),
            content_type: content_type.into(),
            content: content.into(),
        }
    }
}

/// The JSON returned by `POST /send` on success.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct SendEmailResponse {
    pub status: String,
    pub message: String,
}

/// The JSON returned by mailman on error: `{"error": "..."}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct ErrorResponse {
    pub error: String,
}

/// Errors returned by the mailman client.
#[derive(Debug)]
pub enum Error {
    /// No process-global client has been configured and the environment does
    /// not supply `MAILMAN_URL` / `MAILMAN_API_TOKEN`.
    NotConfigured,
    /// The supplied base URL could not be parsed.
    InvalidUrl(String),
    /// The underlying HTTP request failed (connection, TLS, timeout, …).
    #[cfg(feature = "client")]
    Http(reqwest::Error),
    /// The server responded with a non-success status. `message` is the
    /// server's `{"error": "..."}` text when present, otherwise the raw body.
    Status { status: u16, message: String },
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotConfigured => write!(
                f,
                "mailman is not configured; call mailman::setup() or set MAILMAN_URL and MAILMAN_API_TOKEN"
            ),
            Self::InvalidUrl(s) => write!(f, "invalid mailman URL: {s}"),
            #[cfg(feature = "client")]
            Self::Http(e) => write!(f, "http error: {e}"),
            Self::Status { status, message } => {
                if message.is_empty() {
                    write!(f, "mailman server returned {status}")
                } else {
                    write!(f, "mailman server returned {status}: {message}")
                }
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            #[cfg(feature = "client")]
            Self::Http(e) => Some(e),
            _ => None,
        }
    }
}

#[cfg(feature = "client")]
mod client;
#[cfg(feature = "client")]
pub use client::{Client, configured_url, from_env, send, setup};