# Send from any language

The API is plain HTTPS and JSON, so any language that can make a request can send. Each program below sends one email, handles a refusal and reads your sent mail page by page.

## What every request carries

- The base URL `https://api.rasket.com`, with paths such as `/emails` straight after it.
- `Authorization: Bearer` and your key, which starts with `rk_`. The programs read it from `RASKET_API_KEY`. [Authentication](https://www.rasket.com/docs/authentication) says which key to make.
- A `User-Agent` that names your app. A request without one is refused, and some HTTP libraries send none unless you set it.
- On a send, an `Idempotency-Key` taken from the work itself, such as an order number, so a retry within 24 hours returns the first answer instead of sending twice. See [idempotency](https://www.rasket.com/docs/idempotency).

A refusal is a status of 400 or more with a JSON body of `statusCode`, `name` and `message`. Branch on `name`; the [errors](https://www.rasket.com/docs/errors) page lists every one. Each program prints it as `rasket: status name: message` and exits with 1.

A list answers `has_more` and `data`. Ask for up to 100 items with `limit`, and pass the last item's id as `after` for the next page. The programs stop after three pages. A longer walk should wait out `retry-after` when it meets the [rate limit](https://www.rasket.com/docs/rate-limits) of 10 requests a second . [Pagination](https://www.rasket.com/docs/pagination) has the rest.

> Each program sends from `orders@send.acme.example` to an example address. Change both before you run it: send from a domain you have verified, or from your team's managed address to someone on your team.

## The programs

Pick your language, set the key, save the file and run it. It prints `sent` and the new email's id, then the id and subject of your most recent emails.

Go (main.go):

```bash
export RASKET_API_KEY="rk_your_key"
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
)

const baseURL = "https://api.rasket.com"

// apiError is the body every refusal carries.
type apiError struct {
	StatusCode int    `json:"statusCode"`
	Name       string `json:"name"`
	Message    string `json:"message"`
}

func (e *apiError) Error() string {
	return fmt.Sprintf("%d %s: %s", e.StatusCode, e.Name, e.Message)
}

// call makes one request and decodes the JSON answer into out.
func call(method, path string, body any, headers map[string]string, out any) error {
	var payload io.Reader
	if body != nil {
		encoded, err := json.Marshal(body)
		if err != nil {
			return err
		}
		payload = bytes.NewReader(encoded)
	}
	request, err := http.NewRequest(method, baseURL+path, payload)
	if err != nil {
		return err
	}
	request.Header.Set("Authorization", "Bearer "+os.Getenv("RASKET_API_KEY"))
	request.Header.Set("User-Agent", "acme-billing/1.0")
	request.Header.Set("Content-Type", "application/json")
	for name, value := range headers {
		request.Header.Set(name, value)
	}
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	raw, err := io.ReadAll(response.Body)
	if err != nil {
		return err
	}
	if response.StatusCode >= 300 {
		refusal := &apiError{StatusCode: response.StatusCode}
		_ = json.Unmarshal(raw, refusal)
		return refusal
	}
	return json.Unmarshal(raw, out)
}

func main() {
	var sent struct {
		ID string `json:"id"`
	}
	err := call("POST", "/emails", map[string]any{
		"from":    "Acme <orders@send.acme.example>",
		"to":      []string{"ronald.williams@example.com"},
		"subject": "Your order has shipped",
		"html":    "<p>Order 1042 is on its way.</p>",
	}, map[string]string{"Idempotency-Key": "order-1042-shipped"}, &sent)
	if err != nil {
		fmt.Fprintln(os.Stderr, "rasket:", err)
		os.Exit(1)
	}
	fmt.Println("sent", sent.ID)

	// Walk the list, three pages at most: pass the last id as `after` while has_more is true.
	after := ""
	for page := 0; page < 3; page++ {
		query := url.Values{"limit": {"100"}}
		if after != "" {
			query.Set("after", after)
		}
		var list struct {
			HasMore bool `json:"has_more"`
			Data    []struct {
				ID      string `json:"id"`
				Subject string `json:"subject"`
			} `json:"data"`
		}
		if err := call("GET", "/emails?"+query.Encode(), nil, nil, &list); err != nil {
			fmt.Fprintln(os.Stderr, "rasket:", err)
			os.Exit(1)
		}
		for _, email := range list.Data {
			fmt.Println(email.ID, email.Subject)
		}
		if !list.HasMore || len(list.Data) == 0 {
			break
		}
		after = list.Data[len(list.Data)-1].ID
	}
}
```

```bash
go run main.go
```

PHP (send.php):

```bash
export RASKET_API_KEY="rk_your_key"
```

```php
<?php

const BASE_URL = 'https://api.rasket.com';

function rasket(string $method, string $path, ?array $body = null, array $headers = []): array
{
    $lines = [
        'Authorization: Bearer ' . getenv('RASKET_API_KEY'),
        'User-Agent: acme-billing/1.0',
        'Content-Type: application/json',
    ];
    foreach ($headers as $name => $value) {
        $lines[] = "$name: $value";
    }
    $context = stream_context_create(['http' => [
        'method' => $method,
        'header' => implode("\r\n", $lines),
        'content' => $body === null ? '' : json_encode($body),
        // Read the body of a refusal too, rather than failing on the status.
        'ignore_errors' => true,
    ]]);
    $raw = file_get_contents(BASE_URL . $path, false, $context);
    if ($raw === false) {
        throw new RuntimeException('the request did not complete');
    }
    preg_match('{^HTTP/\S+ (\d{3})}', $http_response_header[0], $match);
    $status = (int) $match[1];
    $answer = json_decode($raw, true) ?? [];
    if ($status >= 300) {
        // Every refusal carries statusCode, name and message.
        throw new RuntimeException("$status {$answer['name']}: {$answer['message']}");
    }
    return $answer;
}

try {
    $sent = rasket('POST', '/emails', [
        'from' => 'Acme <orders@send.acme.example>',
        'to' => ['ronald.williams@example.com'],
        'subject' => 'Your order has shipped',
        'html' => '<p>Order 1042 is on its way.</p>',
    ], ['Idempotency-Key' => 'order-1042-shipped']);
    echo "sent {$sent['id']}\n";

    // Walk the list, three pages at most: pass the last id as `after` while has_more is true.
    $after = null;
    $pages = 0;
    do {
        $query = http_build_query(['limit' => 100] + ($after === null ? [] : ['after' => $after]));
        $page = rasket('GET', "/emails?$query");
        foreach ($page['data'] as $email) {
            echo "{$email['id']} {$email['subject']}\n";
        }
        $last = end($page['data']);
        $after = $last === false ? null : $last['id'];
    } while ($page['has_more'] && $after !== null && ++$pages < 3);
} catch (RuntimeException $error) {
    fwrite(STDERR, "rasket: {$error->getMessage()}\n");
    exit(1);
}
```

```bash
php send.php
```

Ruby (send.rb):

```bash
export RASKET_API_KEY="rk_your_key"
```

```ruby
require "json"
require "net/http"
require "uri"

BASE_URL = "https://api.rasket.com"
METHODS = { "GET" => Net::HTTP::Get, "POST" => Net::HTTP::Post }.freeze

class RasketError < StandardError; end

def rasket(method, path, body: nil, headers: {})
  uri = URI(BASE_URL + path)
  request = METHODS.fetch(method).new(uri)
  request["Authorization"] = "Bearer #{ENV.fetch('RASKET_API_KEY')}"
  request["User-Agent"] = "acme-billing/1.0"
  request["Content-Type"] = "application/json"
  headers.each { |name, value| request[name] = value }
  request.body = JSON.generate(body) unless body.nil?

  response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
  answer = JSON.parse(response.body.to_s.empty? ? "{}" : response.body)
  # Every refusal carries statusCode, name and message.
  raise RasketError, "#{response.code} #{answer['name']}: #{answer['message']}" unless response.is_a?(Net::HTTPSuccess)

  answer
end

begin
  sent = rasket("POST", "/emails",
                body: {
                  from: "Acme <orders@send.acme.example>",
                  to: ["ronald.williams@example.com"],
                  subject: "Your order has shipped",
                  html: "<p>Order 1042 is on its way.</p>"
                },
                headers: { "Idempotency-Key" => "order-1042-shipped" })
  puts "sent #{sent['id']}"

  # Walk the list, three pages at most: pass the last id as `after` while has_more is true.
  after = nil
  3.times do
    query = URI.encode_www_form({ limit: 100, after: after }.compact)
    page = rasket("GET", "/emails?#{query}")
    page["data"].each { |email| puts "#{email['id']} #{email['subject']}" }
    break unless page["has_more"] && !page["data"].empty?

    after = page["data"].last["id"]
  end
rescue RasketError => error
  warn "rasket: #{error.message}"
  exit 1
end
```

```bash
ruby send.rb
```

Java (Send.java):

```bash
export RASKET_API_KEY="rk_your_key"
```

```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;

public class Send {
    static final String BASE_URL = "https://api.rasket.com";
    static final HttpClient HTTP = HttpClient.newHttpClient();
    static final ObjectMapper JSON = new ObjectMapper();

    static class RasketException extends Exception {
        RasketException(String message) {
            super(message);
        }
    }

    static JsonNode rasket(String method, String path, Object body, Map<String, String> headers)
            throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(BASE_URL + path))
                .header("Authorization", "Bearer " + System.getenv("RASKET_API_KEY"))
                .header("User-Agent", "acme-billing/1.0")
                .header("Content-Type", "application/json")
                .method(method, body == null
                        ? HttpRequest.BodyPublishers.noBody()
                        : HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)));
        headers.forEach(request::header);
        HttpResponse<String> response =
                HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString());
        JsonNode answer = JSON.readTree(response.body().isEmpty() ? "{}" : response.body());
        if (response.statusCode() >= 300) {
            // Every refusal carries statusCode, name and message.
            throw new RasketException(response.statusCode() + " " + answer.path("name").asText()
                    + ": " + answer.path("message").asText());
        }
        return answer;
    }

    public static void main(String[] args) throws Exception {
        try {
            JsonNode sent = rasket("POST", "/emails", Map.of(
                    "from", "Acme <orders@send.acme.example>",
                    "to", List.of("ronald.williams@example.com"),
                    "subject", "Your order has shipped",
                    "html", "<p>Order 1042 is on its way.</p>"),
                    Map.of("Idempotency-Key", "order-1042-shipped"));
            System.out.println("sent " + sent.get("id").asText());

            // Walk the list, three pages at most: pass the last id as `after` while has_more is true.
            String after = null;
            for (int pages = 0; pages < 3; pages++) {
                String query = "?limit=100" + (after == null ? "" : "&after=" + after);
                JsonNode page = rasket("GET", "/emails" + query, null, Map.of());
                JsonNode data = page.get("data");
                for (JsonNode email : data) {
                    System.out.println(email.get("id").asText() + " " + email.path("subject").asText());
                }
                if (!page.path("has_more").asBoolean() || data.isEmpty()) {
                    break;
                }
                after = data.get(data.size() - 1).get("id").asText();
            }
        } catch (RasketException error) {
            System.err.println("rasket: " + error.getMessage());
            System.exit(1);
        }
    }
}
```

```bash
java -cp jackson-databind.jar:jackson-core.jar:jackson-annotations.jar Send.java
```

C# (Program.cs):

```bash
export RASKET_API_KEY="rk_your_key"
```

```csharp
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json.Nodes;

var http = new HttpClient { BaseAddress = new Uri("https://api.rasket.com") };
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("RASKET_API_KEY"));
// HttpClient sends no User-Agent of its own, and a request without one is refused.
http.DefaultRequestHeaders.UserAgent.ParseAdd("acme-billing/1.0");

async Task<JsonNode> Rasket(HttpMethod method, string path, object? body = null, string? idempotencyKey = null)
{
    using var request = new HttpRequestMessage(method, path);
    if (body is not null) request.Content = JsonContent.Create(body);
    if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey);
    using var response = await http.SendAsync(request);
    var raw = await response.Content.ReadAsStringAsync();
    var answer = JsonNode.Parse(raw.Length == 0 ? "{}" : raw)!;
    // Every refusal carries statusCode, name and message.
    if (!response.IsSuccessStatusCode)
        throw new RasketException($"{(int)response.StatusCode} {answer["name"]}: {answer["message"]}");
    return answer;
}

try
{
    var sent = await Rasket(HttpMethod.Post, "/emails", new
    {
        from = "Acme <orders@send.acme.example>",
        to = new[] { "ronald.williams@example.com" },
        subject = "Your order has shipped",
        html = "<p>Order 1042 is on its way.</p>",
    }, idempotencyKey: "order-1042-shipped");
    Console.WriteLine($"sent {sent["id"]}");

    // Walk the list, three pages at most: pass the last id as `after` while has_more is true.
    string? after = null;
    for (var pages = 0; pages < 3; pages++)
    {
        var page = await Rasket(HttpMethod.Get, "/emails?limit=100" + (after is null ? "" : $"&after={after}"));
        var data = page["data"]!.AsArray();
        foreach (var email in data) Console.WriteLine($"{email!["id"]} {email["subject"]}");
        if (page["has_more"]?.GetValue<bool>() != true || data.Count == 0) break;
        after = data[^1]!["id"]!.GetValue<string>();
    }
}
catch (RasketException error)
{
    Console.Error.WriteLine($"rasket: {error.Message}");
    return 1;
}
return 0;

class RasketException(string message) : Exception(message);
```

```bash
dotnet run
```

Rust (src/main.rs):

```bash
export RASKET_API_KEY="rk_your_key"
```

```rust
use reqwest::blocking::Client;
use reqwest::Method;
use serde_json::{json, Value};

const BASE_URL: &str = "https://api.rasket.com";

fn rasket(
    client: &Client,
    method: Method,
    path: &str,
    body: Option<Value>,
    idempotency_key: Option<&str>,
) -> Result<Value, String> {
    let key = std::env::var("RASKET_API_KEY").map_err(|_| "RASKET_API_KEY is not set")?;
    let mut request = client
        .request(method, format!("{BASE_URL}{path}"))
        .bearer_auth(key)
        // reqwest sends no User-Agent of its own, and a request without one is refused.
        .header("User-Agent", "acme-billing/1.0");
    if let Some(body) = body {
        request = request.json(&body);
    }
    if let Some(idempotency_key) = idempotency_key {
        request = request.header("Idempotency-Key", idempotency_key);
    }
    let response = request.send().map_err(|error| error.to_string())?;
    let status = response.status();
    let answer: Value = response.json().unwrap_or(Value::Null);
    if !status.is_success() {
        // Every refusal carries statusCode, name and message.
        return Err(format!(
            "{} {}: {}",
            status.as_u16(),
            answer["name"].as_str().unwrap_or("unknown"),
            answer["message"].as_str().unwrap_or("")
        ));
    }
    Ok(answer)
}

fn run(client: &Client) -> Result<(), String> {
    let email = json!({
        "from": "Acme <orders@send.acme.example>",
        "to": ["ronald.williams@example.com"],
        "subject": "Your order has shipped",
        "html": "<p>Order 1042 is on its way.</p>"
    });
    let sent = rasket(client, Method::POST, "/emails", Some(email), Some("order-1042-shipped"))?;
    println!("sent {}", sent["id"].as_str().unwrap_or(""));

    // Walk the list, three pages at most: pass the last id as `after` while has_more is true.
    let mut after: Option<String> = None;
    for _ in 0..3 {
        let path = match &after {
            Some(id) => format!("/emails?limit=100&after={id}"),
            None => "/emails?limit=100".to_string(),
        };
        let page = rasket(client, Method::GET, &path, None, None)?;
        let data = page["data"].as_array().cloned().unwrap_or_default();
        for email in &data {
            println!("{} {}", email["id"].as_str().unwrap_or(""), email["subject"].as_str().unwrap_or(""));
        }
        if page["has_more"] != Value::Bool(true) || data.is_empty() {
            break;
        }
        after = data.last().and_then(|email| email["id"].as_str()).map(String::from);
    }
    Ok(())
}

fn main() {
    if let Err(message) = run(&Client::new()) {
        eprintln!("rasket: {message}");
        std::process::exit(1);
    }
}
```

```bash
cargo run
```

Elixir (send.exs):

```bash
export RASKET_API_KEY="rk_your_key"
```

```elixir
Mix.install([{:req, "~> 0.5"}])

defmodule Rasket do
  def call(options) do
    client =
      Req.new(
        base_url: "https://api.rasket.com",
        auth: {:bearer, System.fetch_env!("RASKET_API_KEY")},
        headers: [user_agent: "acme-billing/1.0"]
      )

    case Req.request(client, options) do
      {:ok, %Req.Response{status: status, body: body}} when status in 200..299 ->
        {:ok, body}

      # Every refusal carries statusCode, name and message.
      {:ok, %Req.Response{status: status, body: body}} ->
        {:error, "#{status} #{body["name"]}: #{body["message"]}"}

      {:error, exception} ->
        {:error, Exception.message(exception)}
    end
  end

  # Walk the list, three pages at most: pass the last id as `after` while has_more is true.
  def list_emails(cursor \\ nil, pages_left \\ 3) do
    params = if cursor, do: [limit: 100, after: cursor], else: [limit: 100]

    with {:ok, page} <- call(method: :get, url: "/emails", params: params) do
      Enum.each(page["data"], fn email -> IO.puts("#{email["id"]} #{email["subject"]}") end)

      case {page["has_more"] and pages_left > 1, List.last(page["data"])} do
        {true, %{"id" => last}} -> list_emails(last, pages_left - 1)
        _ -> :ok
      end
    end
  end
end

email = %{
  from: "Acme <orders@send.acme.example>",
  to: ["ronald.williams@example.com"],
  subject: "Your order has shipped",
  html: "<p>Order 1042 is on its way.</p>"
}

result =
  with {:ok, sent} <-
         Rasket.call(
           method: :post,
           url: "/emails",
           json: email,
           headers: [idempotency_key: "order-1042-shipped"]
         ) do
    IO.puts("sent #{sent["id"]}")
    Rasket.list_emails()
  end

with {:error, message} <- result do
  IO.puts(:stderr, "rasket: #{message}")
  System.halt(1)
end
```

```bash
elixir send.exs
```

curl (send.sh):

```bash
export RASKET_API_KEY="rk_your_key"
```

```bash
#!/bin/sh
# Send. --fail-with-body exits non-zero on a refusal and still prints its JSON (jq formats it).
sent=$(curl --fail-with-body -sS https://api.rasket.com/emails \
  -H "Authorization: Bearer $RASKET_API_KEY" \
  -H "User-Agent: acme-billing/1.0" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1042-shipped" \
  -d '{
    "from": "Acme <orders@send.acme.example>",
    "to": ["ronald.williams@example.com"],
    "subject": "Your order has shipped",
    "html": "<p>Order 1042 is on its way.</p>"
  }') || { echo "$sent" | jq -r '"rasket: \(.statusCode) \(.name): \(.message)"' >&2; exit 1; }
echo "$sent" | jq -r '"sent \(.id)"'

# Walk the list, three pages at most: pass the last id as `after` while has_more is true.
after=""
for _ in 1 2 3; do
  page=$(curl --fail-with-body -sS "https://api.rasket.com/emails?limit=100${after:+&after=$after}" \
    -H "Authorization: Bearer $RASKET_API_KEY" \
    -H "User-Agent: acme-billing/1.0") ||
    { echo "$page" | jq -r '"rasket: \(.statusCode) \(.name): \(.message)"' >&2; exit 1; }
  echo "$page" | jq -r '.data[] | "\(.id) \(.subject)"'
  [ "$(echo "$page" | jq -r '.has_more')" = "true" ] || break
  after=$(echo "$page" | jq -r '.data[-1].id')
done
```

```bash
sh send.sh
```

| Language | What to install | Tested with |
| --- | --- | --- |
| Go | Nothing: the standard library has everything it needs. | Go 1.27 |
| PHP | Nothing: PHP's own HTTPS stream sends the request, so the curl extension is not needed. | PHP 8.3 |
| Ruby | Nothing: net/http and json come with Ruby. | Ruby 2.6 |
| Java | Jackson, to read JSON: add com.fasterxml.jackson.core:jackson-databind to your build, or put its three jars beside the file. | Java 21 and Jackson 2.19 |
| C# | Nothing: HttpClient and System.Text.Json are part of .NET. Make a console project and replace its Program.cs. `dotnet new console -o send` | .NET 10 |
| Rust | Two crates: reqwest for HTTP and serde_json for the body. `cargo new send && cd send && cargo add reqwest --features blocking,json && cargo add serde_json` | Rust 1.100, reqwest 0.13 and serde_json 1 |
| Elixir | Nothing by hand: Mix.install fetches Req the first time the script runs. | Elixir 1.18, OTP 27 and Req 0.5 |
| curl | curl 7.76 or later, for --fail-with-body, and jq to read the answers. | curl 8.7 and jq 1.7 |

> The key `order-1042-shipped` stands for one order. Run a program twice and the second run answers with the first email's id and sends nothing. Change the email and run it again within 24 hours, and the key refuses it with `409` `invalid_idempotent_request`: use a new key for new work. The [quickstart](https://www.rasket.com/docs/quickstart)'s shorter files leave the key out on purpose, because they are made to be run again.

## Where to go next

- Rather use a client library? See [Node](https://www.rasket.com/docs/sdk/node), [Python](https://www.rasket.com/docs/sdk/python), [Go](https://www.rasket.com/docs/sdk/go), [PHP](https://www.rasket.com/docs/sdk/php), [Ruby](https://www.rasket.com/docs/sdk/ruby), [Java](https://www.rasket.com/docs/sdk/java), [.NET](https://www.rasket.com/docs/sdk/dotnet), [Rust](https://www.rasket.com/docs/sdk/rust). Each page says whether its package can be installed yet.
- Every endpoint, with its fields and answers, is in the [API reference](https://www.rasket.com/docs/api-reference/emails).
- Framework guides walk through a whole app: [Go](https://www.rasket.com/email-api/go), [Rails](https://www.rasket.com/email-api/rails) and [Laravel](https://www.rasket.com/email-api/laravel).
- Moving code from another email API? Read [switching providers](https://www.rasket.com/docs/switching).
