Send with

Send email with Rust

Use reqwest for HTTP and serde_json for the body.

Setup

# Cargo.toml
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
export ROBUSTEMAIL_API_KEY="rb_test_..."

Send an email

use serde_json::{json, Value};
use std::time::Duration;

const API: &str = "https://robustemail.com/api/v2/emails";

/// Sends one email and returns its ID.
async fn send_email(
    client: &reqwest::Client,
    email: &Value,
    idempotency_key: Option<&str>,
) -> Result<String, Box<dyn std::error::Error>> {
    let mut request = client
        .post(API)
        .bearer_auth(std::env::var("ROBUSTEMAIL_API_KEY")?)
        .json(email);
    if let Some(key) = idempotency_key {
        request = request.header("Idempotency-Key", key);
    }

    let response = request.send().await?;
    let status = response.status();
    let body: Value = response.json().await?;
    if !status.is_success() {
        let name = body["name"].as_str().unwrap_or("error");
        let message = body["message"].as_str().unwrap_or("");
        return Err(format!("{name}: {message}").into());
    }

    Ok(body["id"].as_str().unwrap_or_default().to_string())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()?;

    let email = json!({
        "from": "Acme <hello@acme.com>",
        "to": "delivered@sandbox.robustemail.dev",
        "subject": "Welcome to Acme",
        "html": "<h1>Welcome!</h1><p>Thanks for signing up.</p>"
    });

    let id = send_email(&client, &email, Some("welcome-user-1042")).await?;
    println!("Queued {id}");
    Ok(())
}

Create one reqwest::Client and reuse it: it keeps a connection pool.

Next