Rust SDK

Rust SDK

Install the Mailset Rust SDK, send email, verify webhooks and handle errors, with examples that run.

  • Every public command238 commands, each a typed method
  • Typed throughoutStructs and enums, checked by clippy
  • Retries built inTwo more tries, and a send never doubles
  • Timeouts per try30 seconds a try, then tried again
  • Idempotency keysA send repeated with its key goes once
  • Webhook verificationSignatures checked, every event typed
On this page
  1. Requirements
  2. Install
  3. Create a client
  4. Send
  5. Send many
  6. Promotional email
  7. Idempotency
  8. Check the key
  9. Delivery search
  10. Webhooks
  11. Errors
  12. Build the message yourself
  13. Names
  14. Version and licence

Requirements

Runs onRust 1.88+base64 0.23+getrandom 0.4+hmac 0.13+p256 0.14+reqwest 0.13+serde 1+serde_json 1+sha2 0.11+tokio 1+

Install

Add the SDK to your project.

cargo add mailset

Create a client

One client holds one MAILSET_KEY. Make it when your server starts and use it for every call.

Pass the key in

Where your app keeps its secrets elsewhere, hand the key to the client yourself. A token goes the same way.

Options

Everything has a default. Name a credential, an org, how long a try may take and how often a call is tried again, only where yours differ.

Authentication

Rust
use mailset::Client;

// Reads MAILSET_KEY, else MAILSET_TOKEN.
let mailset = Client::from_env()?;
// One client for the whole server: its clones
// share its connections. Nothing is sent until
// you call a method.
Pass the key in
use mailset::Client;

// From your secret store or config, never in the code.
// Or `.token(…)` with an API token.
let mailset = Client::builder()
    .key(&config.mailset_key)
    .build()?;
Options
use std::time::Duration;

// Or `.token(…)` with MAILSET_TOKEN.
let key = std::env::var("MAILSET_KEY");
let mailset = mailset::Client::builder()
    .key(key.unwrap_or_default())
    // The key names it: rarely needed.
    .base_url("https://mailset.app")
    // The org commands are about, for a person
    // in more than one.
    .org("org_7c2e9a4f")
    // Each try may take 10 seconds. A network
    // failure, a timeout or a 5xx is tried again,
    // 3 times (2 unless told).
    .timeout(Duration::from_secs(10))
    .max_retries(3)
    // A command that needs a passkey waits for
    // someone to approve it.
    .on_approval(|approval| async move {
        println!("Approve it: {}", approval.url);
    })
    .build()?;

println!("{:?}", mailset.key().check().await?);

Send

Send one message and get its receipt. A message Mailset refuses is an error with a code, never a silent drop.

Give sign-in codes a deadlineHonor unsubscribes and complaintsHandle skipped recipientsGuide for Rust

Rust
use mailset::{Client, Message};

// Reads MAILSET_KEY from the environment.
let mailset = Client::from_env()?;

let message = Message::builder()
    .from("Acme <moc.elpmaxe@olleh>")
    .to("gro.elpmaxe@ana")
    .subject("Your Acme code")
    .text("Your code is 123456.")
    .html("<p>Your code is <b>123456</b>.</p>")
    .deliver_by("10m");
let sent = mailset.send(message).await?;

println!("{} {:?}", sent.id, sent.status);

Send many

Send several messages in one call and get one result per message, in the same order. A refused message never stops the rest.

Send many messages at once

Rust
use mailset::{Client, Message};

// Reads MAILSET_KEY from the environment.
let mailset = Client::from_env()?;

let invoice = |to: &str, number: u32| {
    Message::builder()
        .from("Acme <moc.elpmaxe@olleh>")
        .to(to)
        .subject("Your invoice")
        .text(format!("Invoice {number} is ready."))
};
let messages = [
    invoice("gro.elpmaxe@ana", 8842),
    invoice("gro.elpmaxe@neb", 8843),
];
let results = mailset.send_many(messages).await?;

for result in results {
    match result {
        Ok(sent) => println!("{}", sent.id),
        Err(not) => eprintln!("{}", not.error),
    }
}

Promotional email

Send a newsletter or an offer with mode: 'promotional'. {{mailset_unsubscribe}} is a placeholder Mailset fills in for each message, with a signed one-click unsubscribe link unique to that recipient and that message. You never generate the link, and Mailset adds the matching List-Unsubscribe and List-Unsubscribe-Post headers itself.

Honor unsubscribes and complaintsHandle skipped recipients

Rust
use mailset::{Client, Message, Mode};

// Reads MAILSET_KEY from the environment.
let mailset = Client::from_env()?;

let text = [
    "Three new things this month.",
    "",
    "Leave this list: {{mailset_unsubscribe}}",
]
.join("\n");

let html = [
    "<p>Three new things this month.</p>",
    "<a href=\"{{mailset_unsubscribe}}\">Leave</a>",
]
.join("\n");
What Ana receives
Headers Mailset adds
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
Text part
Three new things this month.

Leave this list: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
HTML part

Three new things this month.

Leave this list

A sample link. Mailset makes a new one for every message.

What Ana receives without the placeholder
Text part
Three new things this month.

Unsubscribe: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
HTML part

Three new things this month.

Unsubscribe

Mailset adds the last line of each part. The headers are the same.

Idempotency

Name a send with idempotency_key, and sending it again after a timeout or a crash can’t send it twice.

Retry without sending twice

Rust
use mailset::{Client, Message};

// Reads MAILSET_KEY from the environment.
let mailset = Client::from_env()?;

let receipt = Message::builder()
    .from("Acme <moc.elpmaxe@olleh>")
    .to("gro.elpmaxe@ana")
    .subject("Your receipt")
    .text("Thanks for your order.")
    .idempotency_key("receipt-8842")
    .build();

let first = mailset.send(&receipt).await?;
// After a timeout or a crash, send it again.
// The same key answers the first receipt,
// and nothing goes out twice.
let again = mailset.send(&receipt).await?;

println!("{}", first.id == again.id);

Check the key

Ask what the key may do now. Call it when your server starts and once a day: each call keeps the key alive.

Keep a key alive

Rust
use mailset::types::SendingState;
use mailset::Client;

// Reads MAILSET_KEY from the environment.
let mailset = Client::from_env()?;

// When the server starts, and once a day.
let status = mailset.key().check().await?;

if let Some(paused) = &status.paused {
    eprintln!("Paused: {paused}");
}
println!("Works until {} (ms)", status.expires_at);
// A mailbox key sends as its mailbox.
for b in &status.mailboxes {
    if b.sending != SendingState::Ready {
        eprintln!("{} {}", b.address, b.sending);
    }

Delivery search

Look up what became of the mail this key sent, one line per recipient. For a support question or a nightly check.

Handle bounces

Rust
use mailset::{Client, DeliverySearch};

// Reads MAILSET_KEY from the environment.
let mailset = Client::from_env()?;

// Did Ana get her receipt?
let search = DeliverySearch::new()
    .recipient("gro.elpmaxe@ana")
    .since("2026-11-30");
let page = mailset.delivery().search(search).await?;

for line in &page.lines {
    println!("{} {:?}", line.status, line.reason);
}
// Pass `next` back as `cursor` for the page after.
println!("{:?}", page.next);

Webhooks

Check that a request came from Mailset and read its events. It needs no key and no client, so a service that only receives events uses it alone.

In a web framework

The signature covers the body exactly as it arrived. Read the raw body before anything parses it, and hand that to the check: a body parsed as JSON and written out again no longer matches.

WebhooksHandle bounces

Rust
use mailset::webhooks::{self, Event};

/// Your hook's route, in any framework: the raw body
/// as it came, and the `Mailset-Signature` header.
/// Answers the status to reply with.
pub fn handle(
    body: &[u8],
    signature: Option<&str>,
) -> u16 {
    let secret = std::env::var("MAILSET_HOOK_SECRET");
    let secret = secret.unwrap_or_default();
    let verified =
        webhooks::verify(body, signature, &secret);
    let Ok(events) = verified else {
        return 401;
    };
    for event in events {
        let Event::Bounced(bounced) = event else {
In a web framework
use axum::body::Bytes;
use axum::http::{HeaderMap, StatusCode};
use mailset::webhooks::{self, Event};

// The signature covers the body exactly as it came:
// take it as `Bytes`. A `Json` extractor would parse
// it first and lose the bytes it was made over.
pub async fn mailset_hook(
    headers: HeaderMap,
    body: Bytes,
) -> StatusCode {
    let secret = std::env::var("MAILSET_HOOK_SECRET");
    let secret = secret.unwrap_or_default();
    let verified =
        webhooks::verify(&body, &headers, &secret);
    let Ok(events) = verified else {
        return StatusCode::UNAUTHORIZED;
    };

Errors

Every refusal is one kind of error. Branch on its code, which never changes, and show its message to people.

Retries and timeouts

A network failure or a 5xx answer is tried again, twice unless you set max_retries, waiting longer each time. One try may take 30 seconds unless you set timeout. A refusal is never tried again: the same request gets the same answer.

Errors and limits

Rust
use mailset::{Client, Message};

// Reads MAILSET_KEY from the environment.
let mailset = Client::from_env()?;

let message = Message::builder()
    .from("Acme <moc.elpmaxe@olleh>")
    .to("gro.elpmaxe@ana")
    .subject("Your Acme code")
    .text("Your code is 123456.")
    .deliver_by("10m");

let error = match mailset.send(message).await {
    Ok(sent) => {
        println!("{}", sent.id);
        return Ok(());
    }
    Err(error) => error,
};
if let Some(at) = error.retry_at() {
    println!("Try at {at} (ms)");
} else if error.refusal() == Some("recipient") {
    println!("Ask them to check their address.");
} else {
    // It ends with the docs' link and where to ask.
    eprintln!("{error}");
}

Build the message yourself

Get the message a send would build, without sending it: for a queue of your own, or a call to the API from another service.

messages.submit

Rust
use base64::engine::general_purpose::STANDARD;
use base64::Engine;

let message = mailset::Message::builder()
    .from("Acme <moc.elpmaxe@olleh>")
    .to("gro.elpmaxe@ana")
    .subject("Your Acme code")
    .text("Your code is 123456.")
    .build();
let mime = message.to_mime()?;

// The `data` that messages.submit takes.
let data = STANDARD.encode(&mime.raw);

println!("{} {}", mime.message_id, data.len());

Names

A field keeps its name in every SDK, in each language’s own case. The commands write idempotencyKey, and Rust writes idempotency_key.

Version and licence

This page is for version 0.7.0 of the Rust SDK.

You may use the SDK and change it in your own apps and services, to call Mailset. You may not publish it or pass it on, by itself or inside another library.

Something missing, or not working as this page says? Ask us.