bibby 0.1.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
Documentation
//! Client and types for **Bytebury Mailer** (`https://api.bytebury.com/mailer/v1`).
//!
//! Send transactional emails (with optional idempotency keys, inline base64
//! attachments, or Bytebury Uploader file attachments) and validate email
//! addresses against syntax, MX records, disposable domains, and role lists.

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::{Deserialize, Serialize};

use crate::client::{Bibby, header_pair};
use crate::error::Result;
use crate::services::geo::RiskLevel;

const PRODUCT: &str = "mailer";

/// Client for **Bytebury Mailer**.
///
/// Obtained via [`Bibby::mailer`].
#[derive(Debug, Clone, Copy)]
pub struct MailerClient<'a> {
    client: &'a Bibby,
}

impl<'a> MailerClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    /// Sends a transactional email.
    ///
    /// Use [`crate::email!`] for concise request construction.
    ///
    /// Calls `POST /mailer/v1/emails`.
    pub async fn send(&self, request: &SendEmailRequest) -> Result<SentEmail> {
        self.client.post_json(PRODUCT, "emails", request).await
    }

    /// Sends a transactional email with an `Idempotency-Key` header so safe
    /// retries replay the original response without sending duplicates or
    /// charging again (remembered for 30 days per account).
    ///
    /// Calls `POST /mailer/v1/emails` with `Idempotency-Key: <key>`.
    pub async fn send_idempotent(
        &self,
        request: &SendEmailRequest,
        idempotency_key: &str,
    ) -> Result<SentEmail> {
        let headers = header_pair("idempotency-key", idempotency_key)?;
        self.client
            .post_json_with_headers(PRODUCT, "emails", request, headers)
            .await
    }

    /// Validates an email address (syntax, live MX lookup, disposable domain,
    /// role address, free provider, and risk score). Does not require an SMTP
    /// account.
    ///
    /// Calls `POST /mailer/v1/emails/validate`.
    pub async fn validate(&self, email: &str) -> Result<EmailValidation> {
        #[derive(Serialize)]
        struct Body<'a> {
            email: &'a str,
        }
        self.client
            .post_json(PRODUCT, "emails/validate", &Body { email })
            .await
    }
}

/// File attachment for [`SendEmailRequest`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
    /// Filename shown to recipients (optional when using `uploader_file_id`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
    /// MIME type (e.g. `"application/pdf"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// Base64-encoded file contents (for inline attachments).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    /// Bytebury Uploader file ID (resolved automatically by the gateway).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uploader_file_id: Option<i64>,
}

impl Attachment {
    /// Creates an inline attachment by base64-encoding raw bytes.
    pub fn from_bytes(
        filename: impl Into<String>,
        content_type: impl Into<String>,
        bytes: impl AsRef<[u8]>,
    ) -> Self {
        Self {
            filename: Some(filename.into()),
            content_type: Some(content_type.into()),
            content: Some(STANDARD.encode(bytes.as_ref())),
            uploader_file_id: None,
        }
    }

    /// Attaches a file already stored in your Bytebury Uploader account.
    pub fn from_uploader(file_id: i64) -> Self {
        Self {
            filename: None,
            content_type: None,
            content: None,
            uploader_file_id: Some(file_id),
        }
    }
}

/// Request body for [`MailerClient::send`] and [`MailerClient::send_idempotent`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SendEmailRequest {
    /// Primary recipients (`addr@example.com` or `Name <addr@example.com>`).
    pub to: Vec<String>,
    /// Carbon-copy recipients (Hobby+ plans).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cc: Option<Vec<String>>,
    /// Blind carbon-copy recipients (Hobby+ plans).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bcc: Option<Vec<String>>,
    /// Email subject line.
    pub subject: String,
    /// Plain-text body (at least one of `text` or `html` is required).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// HTML body (at least one of `text` or `html` is required).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
    /// Optional `Reply-To` address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply_to: Option<String>,
    /// Optional file attachments (Builder+ plans; files > 10 MB are auto-linked).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attachments: Option<Vec<Attachment>>,
}

/// Response returned when an email is accepted for delivery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SentEmail {
    /// Primary recipients.
    #[serde(default)]
    pub to: Vec<String>,
    /// Copied recipients.
    #[serde(default)]
    pub cc: Vec<String>,
    /// Hidden recipients.
    #[serde(default)]
    pub bcc: Vec<String>,
    /// Email subject line.
    pub subject: String,
    /// Attached filenames (empty if attachments were auto-linked via Uploader).
    #[serde(default)]
    pub attachments: Vec<String>,
    /// RFC 3339 timestamp when accepted by the mail server.
    pub sent_at: String,
}

/// Reason contributing to an email's risk score.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EmailRiskReason {
    /// Address syntax is invalid.
    InvalidSyntax,
    /// Domain has no MX or A/AAAA mail server records.
    NoMailServer,
    /// Disposable / throwaway email provider.
    Disposable,
    /// Shared role address (e.g. `info@`, `support@`).
    RoleAddress,
    /// DNS lookup timed out.
    DnsTimeout,
}

/// Risk summary inside [`EmailValidation`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmailRisk {
    /// Overall risk tier (`low`, `medium`, or `high`).
    pub level: RiskLevel,
    /// Specific flags triggered during validation.
    #[serde(default)]
    pub reasons: Vec<EmailRiskReason>,
}

/// Response returned by [`MailerClient::validate`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmailValidation {
    /// Original email address submitted.
    pub email: String,
    /// Normalized address, if parseable.
    pub normalized: Option<String>,
    /// Domain part, if parseable.
    pub domain: Option<String>,
    /// Overall validity verdict.
    pub valid: bool,
    /// Whether the address passed RFC syntax validation.
    pub syntax: bool,
    /// Whether the domain has reachable mail servers (`None` on invalid syntax or DNS timeout).
    pub has_mail_server: Option<bool>,
    /// Resolved MX hostnames.
    #[serde(default)]
    pub mx_hosts: Vec<String>,
    /// `true` if the domain is a known disposable email provider.
    pub disposable: bool,
    /// `true` if the local part is a shared role address.
    pub role: bool,
    /// `true` if the domain is a free consumer webmail provider.
    pub free_provider: bool,
    /// Risk tier and reasons.
    pub risk: EmailRisk,
}