Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rullst Mail 📬

Important

This page describes Rullst v13 (13.0.0). The v12 line (rullst-mail@12) reached end of life on 16 October 2026; see the release record. Use a path dependency only for checkout-local review. Items marked (v13) and other recent fixes are not in the published 12.1.x crates.

Vision preserved: additional providers and air-gapped/zero-leak ambitions were not silently removed; see their status and recommendation in the capability ledger.

rullst-mail is Rullst’s transactional email and mailables engine. Official dispatch paths pass through a pre-flight pipeline for CRLF protection, recipient checks, content security scanning, and DLP sanitization before queueing or transport delivery.


Delivery providers (v13)

Version 13 ships four delivery transports: Resend, AWS SES, SendPulse and SMTP, plus the log, memory and offline mock_* drivers for development and tests. The SendGrid, Postmark, Mailjet, Mailtrap and Azure Communication Services transports were removed in 13.0 and remain in the 12.x line. A MAIL_DRIVER or [mail] driver that names one of them fails with MailError::ConfigError naming the driver, never falling back to another driver, and cargo rullst upgrade reports their names as V13-MAIL-REMOVED; see the migration guide row “Mail providers removed”. Mail already queued by 12.x carries no provider name and is delivered by the driver the upgraded worker is configured with.

Any other provider is an application-owned MailDriver: Writing your own mail transport walks through a complete offline example (cargo run -p rullst-mail --example custom_transport), and examples/mail-postmark-driver is a Postmark transport to copy, with its suppression webhook, checked offline by the conformance kit. SendGrid, Mailjet and the other providers v13 removed follow the same shape.

SendPulse shipped in 12.1.0. Set MAIL_DRIVER=sendpulse with SENDPULSE_API_KEY; real delivery requires an explicit verified sender. The crate guide details authentication, attachment/inline limits, tracking configuration, unsubscribe headers and at-least-once retries. No extra feature is needed beyond Mail. Provider acceptance still requires the configured account/domain.

12.1: welcome and password recovery

The 12.1 account-mail guide documents the opt-in PostgreSQL/SQLite account transaction, durable delivery bridge, action-link fix, localized lifecycle templates and signed feedback. These additions shipped in 12.1.0; its Azure Communication Services transport was removed in 13.0. Existing applications must adopt the new store/worker explicitly.

Shared suppression (v13)

Optional postgres (facade mail-postgres) adds PostgresSuppressionStore, a recipient suppression and replay store shared by hosts using one PostgreSQL database. Install the guard in every sending process and worker; it is not enabled automatically. See the shared suppression contract.

✨ Features

  • 🛡️ Typed failures: production delivery paths return MailError; malformed messages and provider configuration fail closed. CI and formal checks remain scoped evidence, not an absolute guarantee.
  • ⚡ Delivery and Test Drivers:
    • Resend (ResendDriver) — Native REST API with scheduled delivery & RFC 8058.
    • SendPulse (SendPulseDriver) — Native transactional REST adapter; see the section above.
    • AWS SES v2 (AwsSesDriver, aws-ses) — official AWS SDK/SigV4 native transport with temporary/rotating credential support, plus offline fixture and an explicit legacy proxy boundary.
    • Native SMTP (SmtpDriver) — Pure async Lettre transport with implicit TLS on port 465 and mandatory STARTTLS on every other port.
    • Memory & MailTrap (MemoryDriver, MailTrap) — Zero-I/O in-memory harness with fluent assertions; it is not the hosted Mailtrap service, whose transport v13 removed.
    • Your own transport — implement MailDriver; see Writing your own mail transport.
    • Log (LogDriver) — Metadata-only terminal and file logging (storage/logs/mail.log): a timestamp, attachment count and scheduling flag, never recipients, subject or body.
  • 🔀 Typed Circuit Breaker & Automatic Failover (FailoverDriver): Fails over only for transport, HTTP 5xx, provider rate-limit, or transient SMTP failures; permanent message/configuration/provider rejection stays on the original error path. SuppressionUnavailable and AttachmentInspectionUnavailable are Transient (retry later) but never failover-eligible. A fallback that returns such an error ends the chain with it; when every driver fails transiently, the result is a Transient error, or RateLimited with the bounded Retry-After when the last driver was rate limited. Every attempt keeps the caller’s tenant context or delivery ID, so a wrapped TenantMailResolver selects the tenant’s driver. Structured tracing exposes bounded decision fields without provider bodies.
  • 🏢 Auth-bound Multi-Tenancy Resolver (TenantMailResolver): Select isolated in-process drivers directly from a trusted Core TenantContext; registry failures and invalid IDs fail closed.
  • 📎 Bounded Attachments & Inline CID Assets: The shared pre-flight contract caps count and byte size, validates safe basenames/MIME/CID metadata and requires every unique inline CID to be referenced by HTML. Resend, native SES, the SES bearer proxy and SMTP serialize the same owned-byte model, and SendPulse its non-inline attachments; transports copy or Base64-encode as required.
  • 🔬 Opt-in Attachment Inspection (AttachmentInspectionGuard): A strict bounded local policy rejects executable magic, spoofed known types, active PDF/SVG, secrets and unsafe text links before transport. Checks follow the case-insensitive declared type, the filename extension and the content signature together, never the declared type alone. A static AttachmentInspector adapter boundary supports an independently operated production scanner.
  • 🚫 Durable Recipient Suppression (sqlite, v13 postgres): SuppressionGuard checks manual, hard-bounce and spam-complaint state before transport. The SQLite store binds verified provider/event identities, detects conflicting replay, enforces immutable quotas transactionally and survives restart or multiple local processes; the v13 PostgreSQL store shares that state across hosts.
  • 📊 Secret-Minimized Delivery Observability: ObservedMailDriver records only a bounded provider label, terminal outcome, latency, attachment count and scheduling/tenant booleans through a non-failing static observer.
  • ⏰ Durable Scheduling (.send_at(), .send_in()): SQLite and Redis queues persist schedules for up to 366 days and never claim early; direct Resend delivery uses provider scheduling and rejects a schedule beyond its documented limit (30 days ahead) with ConfigError before any request. Real SMTP, SendPulse, Log and SES paths reject future direct delivery and must use a durable queue. The Resend and SendPulse offline mocks apply the same schedule rules as their live delivery; the SMTP and SES offline fixtures may retain the timestamp for assertions.
  • 🕵️ Outbound Phishing & Homograph URL Interceptor (.validate_security()): Pre-flight detection of mixed-script Unicode IDN spoofed domains (pаypal.com with Cyrillic characters), checked per DNS label of the link host and user-info only, as the text reads and as a browser resolves the link (tabs and newlines removed, \ read as / for HTTP(S), https:host and scheme-relative \\host forms, percent-encoded and A-label hosts), so single-script IDNs such as παράδειγμα.gr or пример.com and non-Latin query text are allowed while all-lookalike Cyrillic labels under a non-Cyrillic TLD are rejected, and dangerous URI schemes (javascript:, data:text/html).
  • ↩️ Reply-To (.reply_to()): Replies go to another mailbox than the sender, for example the visitor who filled in a contact form. The pipeline validates it like from, and Resend, SendPulse, AWS SES (native and proxy) and SMTP send it (since 13.0.0-alpha.5).
  • 📜 RFC 8058 One-Click List-Unsubscribe: Automatic compliant header injection (List-Unsubscribe, plus List-Unsubscribe-Post: List-Unsubscribe=One-Click only for an HTTPS unsubscribe URL, as RFC 8058 requires). The unsubscribe email must be one bare address and the URL may not contain whitespace, <, > or ", so neither value can add another header entry.
  • 🔤 Automatic Plain-Text Fallback: Automatic HTML-to-plain-text conversion without manual duplication; an absolute HTTP(S) link keeps its target as label <URL> unless the label already is the URL.
  • 🔒 Outbound DLP Secret Scanner: Proactive credential masking (whole-token AKIA/ASIA AWS access key IDs, passwords, API tokens, bearer tokens and PEM private-key blocks of any <label>PRIVATE KEY type, including OpenSSH, EC and encrypted keys) before emails leave your server.
  • 📦 Async Background Worker Queues: Native non-blocking dispatch via rullst-core::queue.
  • 🧪 Explicit offline provider mode: empty or mock_* credentials select DeliveryMode::OfflineMock, never perform network I/O, and are inspectable through OfflineMailMock.
  • 🛠️ Safe CLI Scaffolding: Generates registered facade-based Welcome, Password Reset, OTP, Invoice, custom, bounded payment-receipt, and explicit D+1/D+3/D+7 dunning mailables, refusing unsafe names/collisions and escaping dynamic HTML.
  • 🧾 Payment-Bound PDF Delivery: The opt-in capital-invoice bridge accepts only Capital’s final evidence-bound PaidInvoice, attaches bounded HTML/PDF, applies pre-flight and preserves a stable key for the application outbox.

🚀 Quickstart

1. Composing and Sending an Email

use rullst_mail::{Mail, Message};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let logo_bytes = b"replace with application-owned PNG bytes";

    let message = Message::new()
        .to("[email protected]")
        .from("[email protected]")
        .reply_to("Support <[email protected]>")
        .subject("Welcome to Rullst!")
        .html(r#"
            <h1>Welcome, Alice!</h1>
            <p>Thanks for joining our platform.</p>
            <img src="cid:app_logo" alt="Logo" />
        "#)
        .attach_cid("app_logo", "logo.png", logo_bytes.to_vec(), "image/png")
        .attach_bytes("welcome_guide.pdf", b"%PDF-1.4...".to_vec(), "application/pdf")
        .send_in(std::time::Duration::from_secs(60)) // Deliver in 1 minute
        .unsubscribe_url("https://rullst.dev/unsub/alice");

    // The mandatory pipeline validates and sanitizes before queueing or delivery.
Mail::send(message).await?;

    Ok(())
}

For a schedule that survives process restarts, operate a built-in queue and keep its worker handle alive:

#![allow(unused)]
fn main() {
use rullst_core::queue::{Queue, Worker};
use rullst_mail::{register_mail_handler, Mail, Message};

async fn schedule() -> Result<(), Box<dyn std::error::Error>> {
let queue = Queue::sqlite("sqlite://storage/jobs.db").await?;
let mut worker = Worker::new(&queue).poll_interval(100);
register_mail_handler(&mut worker);
let worker_handle = worker.run()?;

let message = Message::new()
    .to("[email protected]")
    .subject("Scheduled update")
    .text("Delivered after the durable due time")
    .send_in(std::time::Duration::from_secs(60));
Mail::enqueue(&queue, message).await?;

// Keep `worker_handle` in application state; shut it down during graceful exit.
worker_handle.shutdown().await?;
Ok(())
}
}

Execution begins on the first worker poll after the UTC timestamp and remains at-least-once. Queue scheduling does not promise exact wall-clock execution, exactly-once provider delivery, or provider acceptance. Redis promotes scheduled jobs by its server clock, so the worker accepts a claimed job whose timestamp is at most 300 seconds ahead of the worker’s own clock and fails a claim that is earlier than that.

The queue has no handler-requested retry: any delivery error, including a Transient or RateLimited provider failure and its Retry-After, marks the mail job failed with the error text. Nothing is lost silently, but the job is sent again only after Queue::retry_failed_job. Automate that for transient failures, or deliver through an outbox with its own retry policy (as account mail does), when provider blips must be retried without an operator.

Mail::enqueue, and Mail::send after Mail::init_queue, run the pre-flight pipeline and apply the default sender before writing a rullst_mail_send job whose JSON payload is a versioned envelope (schema version 1) holding the optional tenant ID and the prepared message. Queued jobs store attachment bytes as one base64 string per attachment. Workers still accept jobs written with the earlier integer-array encoding, but an older worker cannot read the base64 form, so upgrade workers before producers during a rolling deployment.


2. Resilient Multi-Driver Failover (Circuit Breaker)

#![allow(unused)]
fn main() {
use rullst_mail::drivers::{FailoverDriver, ResendDriver, SendPulseDriver};
use std::time::Duration;

fn build_failover() -> Result<FailoverDriver, rullst_mail::MailError> {
let primary = ResendDriver::try_new("re_...")?;
let fallback_1 = SendPulseDriver::try_new("sendpulse_api_key...")?;

let failover_driver = FailoverDriver::new(primary)
    .with_fallback(fallback_1)
    .with_threshold(3) // Trip circuit after 3 consecutive failures
    .with_cooldown(Duration::from_secs(60)); // Cooldown for 60s
Ok(failover_driver)
}
}

3. Dynamic B2B Multi-Tenancy Routing

#![allow(unused)]
fn main() {
use rullst_core::security::TenantMembership;
use rullst_mail::{Message, ResendDriver, TenantMailResolver};

async fn send_tenant_message(
    message: &Message,
) -> Result<(), Box<dyn std::error::Error>> {
let resolver = TenantMailResolver::new();
let membership = TenantMembership::try_new(["tenant_globex"])?;
let context = membership.select("tenant_globex")?;

// Register tenant-specific API credentials during application configuration.
resolver.register_for_context(
    &context,
    ResendDriver::try_new("re_globex...")?,
)?;

// The context must be derived from trusted authentication/membership state.
resolver.send_for_context(&context, &message).await?;
Ok(())
}
}

The registry is intentionally process-local. Durable encrypted credential storage, rotation, and distribution between instances remain application/deployment concerns.


4. Fast Unit & Integration Testing with MailTrap

#![allow(unused)]
fn main() {
use rullst_mail::{Mail, MailTrap, Message};

#[tokio::test]
async fn test_user_registration_email() {
    Mail::set_driver(Box::new(MailTrap::driver()));
    MailTrap::clear();

    let msg = Message::new()
        .to("[email protected]")
        .subject("Welcome to Rullst!")
        .html("<p>Please verify your email address.</p>")
        .attach_bytes("terms.pdf", b"%PDF...".to_vec(), "application/pdf")
        .unsubscribe_url("https://example.com/unsub/alice");

    Mail::send_now(msg).await.unwrap();

    // Fluent assertions
    MailTrap::assert_sent_to("[email protected]")
        .with_subject("Welcome to Rullst!")
        .with_body_contains("Please verify your email")
        .with_attachment_count(1)
        .with_attachment_named("terms.pdf")
        .with_unsubscribe_url("https://example.com/unsub/alice");
}
}

5. Scaffolding Mailables with CLI

# Generate Welcome & Onboarding email
cargo rullst make:mail WelcomeEmail --welcome

# Generate Time-limited Password Reset email
cargo rullst make:mail PasswordReset --reset

# Generate Two-Factor OTP code email
cargo rullst make:mail OtpVerification --otp

# Generate SaaS Invoice receipt email
cargo rullst make:mail InvoiceReceipt --invoice

# Generate a bounded commercial payment receipt (PaymentReceiptEmail)
cargo rullst make:mail-invoice

# Generate explicit D+1/D+3/D+7 payment-recovery stages
cargo rullst make:mail-dunning

The receipt template enables only the mailer feature. Its international_receipt constructor records an application-confirmed payment and states that it is not a tax authorization; it has no NFS-e branch (v13 removed NFS-e from Rullst). The dunning template does not infer due dates, schedule itself, or mutate access. Both generated build paths run the mandatory mail pre-flight and reject unsafe links; payment evidence, billing state, scheduling, and policy remain application-owned.

For native payment-bound PDF delivery, enable rullst-mail/capital-invoice (or umbrella rullst/capital-mail) and use PaidInvoiceDelivery::prepare, then set the verified sender with .from(sender)? (13.0), which re-runs pre-flight. The subject and PDF name follow the invoice’s title label (Invoice INV-1 and invoice-<key>.pdf, or Recibo … and recibo-<key>.pdf with InvoiceLocale::PtBr/Es); .subject(...)? and .filename(...)? (a name ending in .pdf) replace them (13.0.0-alpha.5). It rejects non-final/mock evidence and recipient/amount/currency substitution. Applications still reconcile webhooks and atomically claim the stable delivery key; provider acceptance and exactly-once delivery are not promised.


6. Pre-Flight Deliverability & Disposable Email Filtering

Prevent sender quota waste and fake user signups with built-in deliverability checks and blocked temporary domains:

#![allow(unused)]
fn main() {
use rullst_mail::{is_disposable_email, validate_email_deliverability, Message};

// 1. Direct email address validation
assert!(validate_email_deliverability("[email protected]").is_ok());
assert!(is_disposable_email("[email protected]"));

// 2. Pre-flight check before dispatching
let msg = Message::new()
    .to("[email protected]")
    .subject("Welcome!");

if msg.is_disposable() {
    eprintln!("Blocked disposable email address!");
}
}

7. Composing inspection, suppression, and observability

The wrappers use static dispatch and may be composed around any MailDriver. Enable rullst-mail/sqlite (or umbrella rullst/mail-sqlite) for the durable local suppression store:

#![allow(unused)]
fn main() {
use rullst_mail::{
    AttachmentInspectionGuard, BoundedMailObserver, LocalAttachmentInspector,
    MailDriver, MemoryDriver, Message, MutableSuppressionStore,
    ObservedMailDriver, SqliteSuppressionStore, SuppressionEvent,
    SuppressionGuard, SuppressionReason,
};
use std::time::{SystemTime, UNIX_EPOCH};

async fn deliver() -> Result<(), Box<dyn std::error::Error>> {
let store = SqliteSuppressionStore::connect(
    "sqlite://storage/mail-suppressions.sqlite",
    100_000,
    500_000,
).await?;

// Only record events after the provider-specific signature was authenticated.
let observed_at = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
store.record(SuppressionEvent::try_new(
    "resend",
    "verified-event-id",
    "[email protected]",
    SuppressionReason::HardBounce,
    observed_at,
)?).await?;

let (transport, _) = MemoryDriver::isolated();
let inspected = AttachmentInspectionGuard::new(
    transport,
    LocalAttachmentInspector::strict(),
);
let suppressed = SuppressionGuard::new(inspected, store);
let observer = BoundedMailObserver::new(10_000)?;
let driver = ObservedMailDriver::try_new("memory", suppressed, observer)?;
driver.send(&Message::new()
    .to("[email protected]")
    .subject("Bounded delivery")
    .text("Hello"))
    .await?;
Ok(())
}
}

SuppressionEvent does not verify a webhook signature: a provider-specific adapter must authenticate the exact event first. SQLite is shared durable local state, not multi-host replication or encrypted storage. Keep replay IDs at least as long as every provider’s redelivery window. The local attachment inspector is a bounded heuristic, not antivirus, sandbox execution, recursive archive inspection or content disarm. The default observer is bounded and process-local; the host owns any external metrics/tracing sink, retention and alerts.


8. Authenticated open/click tracking primitives

Generate versioned, purpose-bound HMAC-SHA256 tracking tokens with a mandatory 32-byte secret and bounded validity. HMAC authenticates but does not encrypt: recipient and target URL remain base64-readable in the current token. Message tracking builders sign the bare address the pipeline delivers to ([email protected] for Alice <[email protected]>), so set to first. The application owns consent, minimization, retention, redirects and applicable privacy-law decisions.

#![allow(unused)]
fn main() {
use rullst_mail::{TrackingEngine, TrackingVerifier, PIXEL_1X1_GIF, Message};
use std::time::Duration;

fn tracking_example() -> Result<(), Box<dyn std::error::Error>> {
let secret = b"replace-with-32-or-more-random-key-bytes";
let now_unix_seconds = 1_800_000_000;

// Fluent open & click tracking injection
let tracked_msg = Message::new()
    .to("[email protected]")
    .subject("Monthly Newsletter")
    .html("<p>Check out our <a href=\"https://rullst.dev/pricing\">pricing</a>.</p>")
    .try_with_open_tracking("https://app.com", secret, "campaign_2026")?
    .try_with_click_tracking("https://app.com", secret)?;

let token = TrackingEngine::try_generate_open_token(
    secret,
    "[email protected]",
    "campaign_2026",
    now_unix_seconds,
)?;

// Default verification enforces a 30-day TTL.
let event = TrackingEngine::verify_open_token(secret, &token)?;
println!("Email opened by {} for campaign {}", event.email, event.campaign_id);

// Endpoints needing single-consumption semantics can reject replay explicitly.
let verifier = TrackingVerifier::new(Duration::from_secs(24 * 60 * 60), 100_000)?;
let event = verifier.verify_open_once(secret, &token, now_unix_seconds)?;
let _ = (tracked_msg, event, PIXEL_1X1_GIF);
Ok(())
}
}

9. Transactional Test Fixtures with MailFactory

Quickly generate standard transactional emails for local preview and testing:

#![allow(unused)]
fn main() {
use rullst_mail::MailFactory;

let welcome_msg = MailFactory::fake_welcome("[email protected]", "Alice", "My SaaS App");
let reset_msg = MailFactory::fake_password_reset("[email protected]", "https://app.com/reset?token=xyz", 15);
let otp_msg = MailFactory::fake_otp("[email protected]", "492015", 5);
let invoice_msg = MailFactory::fake_invoice("[email protected]", "INV-2026-001", 9900, "USD");
let alert_msg = MailFactory::fake_security_alert("[email protected]", "Unrecognized Login", "198.51.100.1", "Chrome / macOS");
}

10. Native AWS SES v2 with SigV4

Enable the opt-in official SDK transport:

[dependencies]
rullst-mail = { version = "13.0.0", features = ["aws-ses"] }
aws-config = "1.11"

MAIL_DRIVER=ses selects native mode when both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY exist. AWS_SESSION_TOKEN is accepted for temporary credentials. Without those variables, the existing empty/mock_* token rule selects the offline fixture; a real AWS_SES_BEARER_TOKEN is usable only with an explicit trusted proxy URL. The proxy receives the SES v2 SendEmail JSON shape, including every attachment and inline CID asset as Content.Simple.Attachments (Base64 RawContent, FileName, ContentType, ContentDisposition and ContentId). It is checked against the same SES field limits and 40 MiB encoded estimate as native mode before any request, and failures return MailError::ValidationError. The proxy must forward attachments or reject the request; Rullst never drops them.

SES does not support SMTPUTF8, so native and proxy requests carry 7-bit ASCII addresses: an internationalized domain becomes its IDNA A-label (maria@bücher.de is sent as [email protected]) and a non-ASCII sender display name becomes RFC 2047 encoded-words (=?UTF-8?B?...?=), while an all-ASCII sender is sent unchanged. A non-ASCII local part cannot be expressed and fails before any request with MailError::ValidationError. (v13)

Long-running services should inject a refreshing credential provider or a caller-built SDK config instead of freezing credentials:

This snippet uses the application’s direct aws-config dependency shown above, which Rullst does not re-export, so the book doctests do not compile it (rust,ignore):

use rullst_mail::{AwsSesDriver, MailDriver, Message, aws_ses_sdk};

async fn deliver() -> Result<(), Box<dyn std::error::Error>> {
let shared = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
let config = aws_ses_sdk::Config::new(&shared);
let driver = AwsSesDriver::from_native_config(config)?;
driver.send(&Message::new()
    .to("[email protected]")
    .from("[email protected]")
    .subject("Signed by AWS SigV4")
    .text("Hello from Rullst"))
    .await?;
Ok(())
}

The application still owns AWS identity/domain verification, sandbox exit, IAM least privilege, quotas, reputation, bounce/complaint handling and monitoring. A successful MessageId is provider acceptance, not proof of inbox delivery. The native adapter rejects SES field limits and an encoded message estimate over 40 MiB before network I/O; provider 429 responses preserve a bounded delta-seconds Retry-After for failover/retry policy.


⚙️ Configuration (Rullst.toml or Environment Variables)

[mail]
driver = "resend" # "log" | "memory" | "smtp" | "resend" | "ses" | "sendpulse"
from = "Acme <[email protected]>" # default sender for messages without `from`

The Mail facade reads each variable below from the process environment first and then from the project’s ./.env, which never overrides the environment, exactly as Server reads DATABASE_URL; driver and from in Rullst.toml come last. LogDriver reads MAIL_LOG_PATH the same way. The staging and production check uses the Server environment precedence (RULLST_ENV, then APP_ENV, from the environment and then .env, then [app] env). A malformed .env fails with MailError::ConfigError without echoing its content.

The settings are read on every facade call, but the driver built from them is reused while they stay the same, so its connection pools and native SES client survive across messages and queue jobs. A changed setting builds a new driver for the next message, Mail::reset_driver() drops the reused one, and MAIL_DRIVER=memory still builds a fresh store per message. (v13)

Environment variables:

  • MAIL_DRIVER: Select active driver (log, memory, smtp, resend, ses or its alias aws_ses, sendpulse). The values of the transports v13 removed (sendgrid, postmark, mailjet, mailjet-sandbox, mailtrap, mailtrap-sandbox, azure-acs) fail with MailError::ConfigError, which names the driver and the migration row, and never fall back to another driver. When neither it nor [mail] driver is set, development and test fall back to log, while staging and production (RULLST_ENV, APP_ENV or [app] env, as above) return MailError::ConfigError instead of logging mail that is never delivered. Select log explicitly to keep metadata-only logging there.
  • MAIL_FROM: Default sender (v13) for Mail facade messages that set no from, such as generated mailables. It takes precedence over [mail] from; an explicit from on the message always wins. Use one address or Name <address> that your provider account has verified. An invalid value fails every facade send with MailError::ConfigError; call Mail::default_sender() at startup to fail fast. Drivers used directly do not read it; the other settings below are read by the facade when it builds a driver, and MAIL_LOG_PATH by LogDriver itself.
  • RESEND_API_KEY: API key for Resend.
  • SENDPULSE_API_KEY: Static API key for SendPulse.
  • AWS_REGION: Region used by native SigV4 signing or SES proxy/mock metadata.
  • AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY: Select native SES when the aws-ses feature is enabled; both must be present.
  • AWS_SESSION_TOKEN: Optional temporary-credential session token.
  • AWS_SES_BEARER_TOKEN: Bearer token for an explicit trusted proxy; it is never sent to AWS as a substitute for SigV4.
  • AWS_SES_ENDPOINT: Native SDK base endpoint or complete proxy send URL; HTTPS is required except for loopback integration tests.
  • MAIL_HOST, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD: SMTP credentials. MAIL_PORT defaults to 25 only when unset or empty; any other value must be an integer from 1 to 65535, or the facade returns MailError::ConfigError.
  • MAIL_LOG_PATH: Path for log file (default: storage/logs/mail.log).

For Resend, SendPulse and the SES fixture/proxy, an empty credential or one beginning with mock_ selects the deterministic offline fallback. Use driver.delivery_mode() and OfflineMailMock::deliveries() to assert this explicitly in tests. The process-wide capture keeps only the newest 1,000 deliveries and at most 64 MiB of their subject, body and attachment bytes, and the first capture in a process logs a mail.offline_mock.active warning. The Resend and SendPulse mocks run the same message checks as their live delivery (sender, schedule and, for SendPulse, body, inline CID, unsubscribe headers and attachment names) before capturing, so a test with mock_* credentials refuses what the provider path refuses.

In staging and production, the Mail facade refuses an empty or unset RESEND_API_KEY, SENDPULSE_API_KEY or SES proxy token (AWS_SES_TOKEN/AWS_SES_BEARER_TOKEN, when no AWS keys select native SES), and an empty MAIL_HOST (an unset one means 127.0.0.1, see below), with MailError::ConfigError, instead of capturing every message in the offline mock and reporting success. An explicit mock_* value stays allowed there, and development and test keep the empty-credential fallback. Drivers built directly with try_new do not read the environment and keep the empty-credential rule above (since 13.0.0-rc.1).

Every real transport needs a sender that the provider account has verified: the message’s from, or, for Mail facade sends, the MAIL_FROM / [mail] from default. Without either, delivery fails with MailError::ConfigError before any request, and the error names both settings. Transports never invent a sender.

SMTP selects the offline fallback only explicitly: an empty or mock_* MAIL_HOST, or a mock_* username or password. A real host without credentials is an unauthenticated relay and receives real delivery, so MAIL_DRIVER=smtp without MAIL_HOST sends to 127.0.0.1:25. A username without a password, or the reverse (blank values count as missing), returns MailError::ConfigError instead of falling back to the mock.

Port 465 uses implicit TLS (SMTPS); every other port, including the facade’s default 25 and the usual submission port 587, requires STARTTLS. Plaintext is never used: a server that does not offer STARTTLS, or presents a certificate that is not valid for MAIL_HOST, fails with a typed transport error, so a local relay needs a certificate valid for the configured host name.


Scope and product boundaries

rullst-mail is a transactional-delivery library, not a marketing CRM or a claim that third-party delivery infrastructure is unnecessary.

Implemented building blocks include:

  • typed message construction and escaped generated templates;
  • explicit SMTP, Resend, SendPulse, log and memory drivers, plus the opt-in official-SDK SES v2 transport and bounded SES proxy/mock adapter;
  • deterministic offline mode for empty or mock_* provider credentials;
  • an in-memory MailTrap and MailFactory fixtures;
  • bounded retry/failover helpers, tenant-driver resolution, attachments, provider-specific scheduling fields, and durable SQLite/Redis due times;
  • opt-in attachment inspection, process-local, shared-local SQLite or (v13) shared PostgreSQL suppression, and content-minimized local delivery observations;
  • HMAC-authenticated (not encrypted) tracking tokens with expiry/replay helpers, URL checks, and bounded secret-redaction heuristics.

These components do not provide deliverability, sender-domain reputation, legal consent, unsubscribe policy, durable campaign orchestration, a visual marketing editor, or a production inbox. Provider acceptance is not proof of delivery. Tracking pixels/links have privacy and consent implications that the application must evaluate for each jurisdiction and use case.

Choose a delivery provider and operational policy based on measured volume, region, data processing terms, bounce/complaint handling, retention, cost, and failover tests. Rullst publishes no universal latency, price, or feature comparison against commercial platforms.

Recipients are parsed once by the pre-flight pipeline. It accepts one bare address, <address> or Name <address> (the name may be quoted), and hands the bare address to suppression, the disposable-domain check and every transport, so a display name is not delivered. Lists, groups, comments, quoted local parts, domain literals and malformed brackets are rejected with MailError::ValidationError. Suppression events and lookups use the same parser; anything it rejects fails closed. Suppression keys compare the domain case-insensitively and key an internationalized domain by its IDNA A-label (bücher.de and xn--bcher-kva.de share one entry); a non-ASCII local part cannot be keyed, so SuppressionGuard rejects it with ValidationError rather than reporting SuppressionUnavailable.

The pre-flight pipeline rejects a subject over 2 KiB, or an HTML or plain-text body over 2 MiB each, with MailError::ValidationError before any content scan. Oversized content is rejected, never truncated. The link, homograph and secret-redaction scans are single forward passes, so their cost grows linearly with the bounded body. They still run on the calling task; bound user-supplied text at the request edge as well.

The local inspector chooses its checks from the declared MIME type (compared case-insensitively), the filename extension and the content signature together. Both policies reject executable magic, executable or script-host extensions (.exe, .bat, .cmd, .ps1, .vbs, .js, .hta, .lnk and similar), SVG by type, extension or content, active PDF content wherever a %PDF- header appears in the first KiB, and a declared type that disagrees with a known extension or signature. strict() also rejects HTML extensions, HTML/script markup or javascript:/vbscript: URIs, unknown extensions, any declared type it does not inspect other than application/octet-stream (so a text/html attachment named invoice.txt is rejected), and opaque formats; allowing_opaque() still accepts HTML and other opaque content. PDF names written with #xx escapes or inside compressed streams are not decoded.

Markup is classified the way a browser parses it, not by its first bytes: a document opening with < is SVG or active (X)HTML by its root element after any XML declaration, processing instruction, comment or DOCTYPE, matched after an optional prefix: (<s:svg>, <h:html>), and by the SVG or XHTML namespace URI anywhere in it, also when written with character references. Markup that declares DTD entities, which can assemble a namespace URI from pieces, is treated as SVG unless its root is html, and a UTF-16 document is read by its byte-order mark. (v13)

Attachment limits are 32 items, 20 MiB per item and 25 MiB of raw bytes in aggregate before transport encoding. Provider/account limits can be lower. The base pipeline validates metadata but treats bytes as opaque. The opt-in local inspector recognizes only its documented bounded formats and heuristics; use a production scanner adapter when malware, archive, sandbox or CDR policy is required.