.NET SDK
Use BillionSend from .NET with the BillionSend NuGet package.
The BillionSend package is the BillionSend client for .NET. It covers every operation of the API reference: sending, domains, contacts, broadcasts, templates, webhooks, inboxes with their threads and drafts, live inbox events and agent sign-up. The source is billionsend/billionsend-dotnet on GitHub.
Install
Needs .NET 8 or newer. The package has no dependencies beyond the .NET runtime: it uses HttpClient and System.Text.Json.
dotnet add package BillionSend --version 0.1.0
Send an email
using BillionSend;
using var client = new BillionSendClient(); // reads BILLIONSEND_API_KEY
var sent = await client.Emails.SendAsync(
new
{
from = "Acme <hello@acme.dev>",
to = new[] { "ana@example.com" },
subject = "Welcome to Acme",
html = "<p>Glad you are here.</p>",
},
new IdempotentRequestOptions { IdempotencyKey = "welcome/ana" });
Console.WriteLine(sent?["id"]);
new BillionSendClient("bs_...") takes the key directly, and new BillionSendClient(new BillionSendOptions { ... }) sets the rest: ApiKey, BaseUrl, Timeout (per attempt, default 60 seconds), MaxRetries, HttpClient (one of your own, from IHttpClientFactory for example, which the client then does not dispose and whose BaseAddress is ignored), Headers (sent with every request) and JsonSerializerOptions. BILLIONSEND_BASE_URL overrides the API URL. One client is safe to share across threads: create it once and keep it for the life of the application.
Method names
Each operation is an async method named after its id in the API reference, the dotted path as a chain of resources in PascalCase with the Async suffix: emails.send is client.Emails.SendAsync, emails.receiving.attachments.list is client.Emails.Receiving.Attachments.ListAsync, and agent.claimEmail is client.Agent.ClaimEmailAsync. emails.metrics is client.Emails.Metrics.GetAsync, beside LinksAsync, CountriesAsync and ClientsAsync.
A method takes the path parameters in order, the request body, the query parameters as a Dictionary<string, object?>, the options for that call and a CancellationToken. A body is any object System.Text.Json can write: an anonymous object, a dictionary, a JsonNode or your own type, whose property names are written in snake_case (ReplyTo becomes reply_to). Query lists go comma-separated, booleans as true and false, and null values are left out. Answers are the parsed JSON body as a JsonNode? with the API’s own field names (sent?["id"]), so the API reference describes them field for field; answer.Deserialize<T>() reads one into your own type.
var page = await client.Emails.Receiving.ListAsync(new Dictionary<string, object?>
{
["limit"] = 20,
["unread"] = "true",
});
foreach (var email in page!["data"]!.AsArray())
{
Console.WriteLine($"{email!["from"]}: {email["subject"]}");
}
Idempotency and retries
The eight sending operations (Emails.SendAsync, Emails.BatchAsync, received-mail ReplyAsync and ForwardAsync, Inboxes.SendAsync, Inboxes.Drafts.SendAsync, thread ReplyAsync and ForwardAsync) always send an Idempotency-Key. Without IdempotencyKey in their IdempotentRequestOptions, each call makes up one (a UUID) that its retries reuse, so a retry after a timeout never sends twice; your own key also makes a repeat from another process safe, and a repeat with the same key and body returns the first answer.
Failures worth retrying are retried twice by default: 429, 5xx, timeouts, network errors, and the 409 concurrent_idempotent_requests answered while the first attempt with the same key is still running. Only requests safe to repeat are retried: GET, PUT, DELETE and the sending operations. The client waits as Retry-After asks (seconds or an HTTP date), and throws at once when it asks for more than a minute; otherwise it backs off exponentially from 0.5 s to 8 s, with jitter. MaxRetries and Timeout are set on the client and can be overridden for one call in its options (new IdempotentRequestOptions { MaxRetries = 0 }); an event stream is timed only until it opens.
Errors
A failed call throws ValidationException (400, 422), AuthenticationException (401, or no key configured, with Name set to missing_api_key before anything is sent), PermissionDeniedException (403), NotFoundException (404), ConflictException (409), RateLimitException (429, with RetryAfter in seconds), ApiException (5xx), ApiConnectionException (no answer: DNS, connection or TLS failure) or ApiTimeoutException (the attempt timed out, a kind of ApiConnectionException). All are in the BillionSend namespace and extend BillionSendException, thrown as itself for any other status, with StatusCode (null when there was no answer), Name (the API’s error name), Message and RequestId, the answer’s x-request-id, which is the request’s id on the dashboard’s Logs page. Cancelling the CancellationToken throws OperationCanceledException, as everywhere in .NET.
try
{
var email = await client.Emails.GetAsync(id);
}
catch (NotFoundException)
{
// no such email
}
catch (BillionSendException error)
{
Console.WriteLine($"{error.StatusCode} {error.Name}: {error.Message} (request {error.RequestId})");
throw;
}
Lists
List methods return one page. Every cursor list also has a ListAllAsync method (SearchAllAsync for thread search) that returns an IAsyncEnumerable<JsonNode>, fetching the next pages as you read, backward when before is set:
await foreach (var contact in client.Contacts.ListAllAsync(new Dictionary<string, object?> { ["limit"] = 100 }))
{
Console.WriteLine(contact["email"]);
}
An agent’s inbox
Wait for new mail on the event stream and reply in its thread:
const string inboxId = "support@acme.dev"; // an inbox id or its address
await using var events = await client.Inboxes.Events.StreamInboxAsync(
inboxId,
new Dictionary<string, object?> { ["types"] = "inbox.email.received" });
await foreach (var item in events)
{
if (item is StreamGapEvent)
{
continue; // events may be missing: read the threads again
}
var ids = ((InboxStreamEvent)item).Payload;
var threadId = (string?)ids?["thread_id"];
var emailId = (string?)ids?["email_id"];
if (threadId is null || emailId is null)
{
continue;
}
await client.Inboxes.Threads.Emails.ReplyAsync(
inboxId,
threadId,
emailId,
new { text = "Thanks, we are on it." },
new IdempotentRequestOptions { IdempotencyKey = $"reply/{emailId}" });
}
StreamInboxAsync returns once the stream is open, or throws the error that refused it, and gives an EventStream to read with await foreach. An InboxStreamEvent has Id, Event (the webhook event name, such as inbox.email.received), Data (the webhook payload’s type, created_at, inbox_id and data) and Payload, the inner data with the ids to read next. The stream reconnects with Last-Event-ID when the connection drops and replays what it missed; keep stream.LastEventId and pass it back as LastEventId in new EventStreamOptions { ... } to resume after a restart. A StreamGapEvent comes once when the stream resumes from more than 24 hours back. MaxReconnects (default 5 failed reconnects in a row) tunes reconnecting, which waits a second, or what the server’s retry field asks, before each attempt; past it the stream throws ApiConnectionException. One inbox’s stream ends after that inbox is deleted or expires; client.Inboxes.Events.StreamAsync follows every inbox the key can read. Leaving the loop, Close() or disposing the stream ends it quietly, and cancelling the token throws OperationCanceledException.
Verify webhooks
Webhook.Verify checks a webhook delivery’s signature and timestamp with the endpoint’s whsec_ secret and returns the parsed event as a JsonNode. Pass the body exactly as it arrived; the headers can be a lookup function (as below), a dictionary or any sequence of name and value pairs, and names match in any case:
// Program.cs (ASP.NET Core)
var secret = Environment.GetEnvironmentVariable("BILLIONSEND_WEBHOOK_SECRET")!;
app.MapPost("/webhooks/billionsend", async (HttpRequest request) =>
{
using var reader = new StreamReader(request.Body);
var body = await reader.ReadToEndAsync();
try
{
var evt = Webhook.Verify(body, name => request.Headers[name], secret);
Console.WriteLine((string?)evt["type"]);
return Results.NoContent();
}
catch (WebhookVerificationException)
{
return Results.BadRequest();
}
});
A delivery older than five minutes is refused (Tolerance in WebhookVerifyOptions changes that), and during a secret rotation either secret verifies.