Rust SDK

Send email from Rust with the exx-sh crate, async on tokio and reqwest. Install, configure, send, handle errors and retries, SMTP and webhooks.

exx-sh is the official Rust client for the exx.sh API. It is async, on tokio and reqwest with rustls. MIT licensed.

Install

cargo add exx-sh                    # the API
cargo add exx-sh --features smtp    # and SMTP

Send an email

use exx_sh::{Exx, SendEmail, Tag};

#[tokio::main]
async fn main() -> Result<(), exx_sh::Error> {
    let exx = Exx::new("")?; // reads EXX_API_KEY

    let sent = exx
        .emails()
        .send(&SendEmail {
            from: "Acme <hello@acme.com>".into(),
            to: vec!["delivered@example.com".into()],
            subject: "Your sign-in link".into(),
            html: Some("<p>Click the link to sign in.</p>".into()),
            text: Some("Click the link to sign in.".into()),
            tags: vec![Tag {
                name: "category".into(),
                value: "sign_in".into(),
            }],
            ..Default::default()
        })
        .await;

    match sent {
        Ok(sent) => {
            println!("{}", sent.id);
            Ok(())
        }
        Err(e) => {
            // e.name is the API's error name, e.g. "validation_error".
            eprintln!("{} ({:?}): {}", e.name, e.status_code, e.message);
            Err(e) // a non-zero exit, like the other samples
        }
    }
}

send_with also takes SendOptions { idempotency_key, stream }. The sending guide explains every field.

Configure the client

Exx::new(key) reads the key from EXX_API_KEY when key is empty. For other settings, Exx::builder(key) takes:

SettingMeaning
base_urlThe API's address
retriesRetries after the first attempt, below
timeoutThe time limit of each attempt
user_agentThe User-Agent header

Handle errors

Errors are exx_sh::Error with name (for a server error too), message and status_code; match on name as the errors guide describes. status_code is None when no answer came back. An answer that did not come from the API (a proxy's error page) keeps its status.

Retries

The client retries rate-limited requests, except a spent daily or monthly quota. It retries server errors and lost answers only when sending again cannot act twice: any request but a POST without an Idempotency-Key. A send the server is still processing (409 concurrent_idempotent_requests) is asked again until it has the answer.

Resources

ResourceMethods
emails()send, get, list, update, cancel, list_attachments and get_attachment; received mail: list_received, get_received, list_received_attachments, get_received_attachment; attempts and transcript (exx only)
emails().verifyan address's syntax, DNS and list findings (exx only, verify addresses)
events()send and send_with (Resend's SendEventOptions and ContactIdOrEmail), create and list_names (exx only) (application events)
workflows()create, get, list, update, remove, publish, pause, resume, duplicate, rotate_signing_secret and schema (exx only, workflows)
workflows().versions()list and get a workflow's published versions
workflows().runs()start (with SendOptions { idempotency_key }), list, get, cancel and cancel_all
batch()send a batch
domains()create, get, list, update, delete and verify domains; UpdateDomain { dmarc_reports }, dmarc_summary, dmarc_reports (exx only)
api_keys()create, list and revoke keys
webhooks()create, get, list, update, delete webhooks and rotate their secret; domains on create and update (exx only)
webhooks().deliveries()list, get and replay a webhook's deliveries (exx only)
templates()create, get, list, update, publish, duplicate, remove; check (exx only)
suppressions()list, add and remove suppressed addresses
metrics()get (the series), providers, reputation (exx only)

SMTP

With the smtp feature, exx_sh::smtp::ExxSmtp sends the same email shape over SMTP with lettre (rustls and the system's trust store).

// SMTP needs the `smtp` feature: exx-sh = { version = "0.2", features = ["smtp"] }.
use exx_sh::smtp::ExxSmtp;
use exx_sh::{SendEmail, SendOptions};

#[tokio::main]
async fn main() -> Result<(), exx_sh::Error> {
    let smtp = ExxSmtp::new("")?; // reads EXX_API_KEY; smtp.exx.sh, port 465 (TLS)

    let email = SendEmail {
        from: "Acme <hello@acme.com>".into(),
        to: vec!["delivered@example.com".into()],
        subject: "Your sign-in link".into(),
        html: Some("<p>Click the link to sign in.</p>".into()),
        text: Some("Click the link to sign in.".into()),
        ..Default::default()
    };
    let options = SendOptions {
        idempotency_key: Some("sign-in/123".into()),
        ..Default::default()
    };
    match smtp.send_with(&email, &options).await {
        Ok(sent) => {
            println!("{}", sent.id); // the same id the API and webhooks use
            Ok(())
        }
        Err(e) => {
            // "smtp_error" (e.smtp_code) for a refusal, "validation_error" for what SMTP
            // cannot carry (tags, scheduling, attachment paths).
            eprintln!("{}: {}", e.name, e.message);
            Err(e)
        }
    }
}

ExxSmtp::builder(key) takes host and port (by default EXX_SMTP_HOST and EXX_SMTP_PORT, then smtp.exx.sh and 465), implicit_tls, timeout and root_certificate_pem. Port 465 is TLS from the start and any other port uses STARTTLS; TLS is always required. A refusal is an Error named smtp_error, with smtp_code.

Webhooks

exx_sh::webhooks::verify checks a delivery against the raw body and returns the event as a serde_json::Value; see the webhooks guide:

use exx_sh::webhooks::{self, WebhookHeaders};

/// Your framework's handler: the raw body (before any JSON parsing) and the three
/// `svix-*` headers. Returns the status to answer.
fn handle(body: &[u8], id: &str, timestamp: &str, signature: &str) -> u16 {
    let secret = std::env::var("EXX_WEBHOOK_SECRET").unwrap_or_default();
    let headers = WebhookHeaders {
        id,
        timestamp,
        signature,
    };
    match webhooks::verify(body, &headers, &secret) {
        Ok(event) => {
            println!("{} {}", event["type"], event["data"]);
            204
        }
        Err(_) => 400,
    }
}

fn main() {
    // A delivery with a wrong signature is refused.
    assert_eq!(handle(b"{}", "msg_1", "0", "v1,AAAA"), 400);
}

On this page