---
title: .NET SDK
description: 用 BillionSend NuGet 套件在 .NET 中使用 BillionSend。
ai:
  exclude: true
---

`BillionSend` 套件是 BillionSend 面向 .NET 的用戶端。它涵蓋 [API 參考](/docs/zh-hant/api-reference)中的全部操作：傳送、網域、聯絡人、群發、範本、Webhook、含會話串與草稿的收件匣、即時的收件匣事件，以及 Agent 註冊。原始碼在 GitHub 上的 [billionsend/billionsend-dotnet](https://github.com/billionsend/billionsend-dotnet)。

## 安裝

需要 .NET 8 或更新版本。除了 .NET 執行階段之外，這個套件沒有其他相依套件：它使用 `HttpClient` 和 `System.Text.Json`。

```sh
dotnet add package BillionSend --version 0.1.0
```

## 傳送郵件

```csharp
using BillionSend;

using var client = new BillionSendClient(); // 讀取 BILLIONSEND_API_KEY

var sent = await client.Emails.SendAsync(
    new
    {
        from = "Acme <hello@acme.dev>",
        to = new[] { "success@simulator.amazonses.com" },
        subject = "Welcome to Acme",
        html = "<p>Glad you are here.</p>",
    },
    new IdempotentRequestOptions { IdempotencyKey = "welcome/ana" });

Console.WriteLine(sent?["id"]);
```

`new BillionSendClient("bs_...")` 直接傳入金鑰，`new BillionSendClient(new BillionSendOptions { ... })` 設定其餘選項：`ApiKey`、`BaseUrl`、`Timeout`（每次嘗試，預設 60 秒）、`MaxRetries`、`HttpClient`（你自己的，例如來自 `IHttpClientFactory` 的，用戶端不會釋放它，它的 `BaseAddress` 也會被忽略）、`Headers`（隨每個請求送出）和 `JsonSerializerOptions`。`BILLIONSEND_BASE_URL` 可以覆寫 API 網址。一個用戶端可以安全地在多個執行緒間共用：只建立一次，並在應用程式的整個生命週期中持續使用。

## 方法命名

每個操作都是一個非同步方法，以它在 [API 參考](/docs/zh-hant/api-reference)中的 id 命名，把以點分隔的路徑寫成 PascalCase 的資源鏈，再加上 `Async` 後綴：`emails.send` 是 `client.Emails.SendAsync`，`emails.receiving.attachments.list` 是 `client.Emails.Receiving.Attachments.ListAsync`，`agent.claimEmail` 是 `client.Agent.ClaimEmailAsync`。`emails.metrics` 是 `client.Emails.Metrics.GetAsync`，與 `LinksAsync`、`CountriesAsync` 和 `ClientsAsync` 並列。

方法依序接受路徑參數、請求本文、以 `Dictionary<string, object?>` 表示的查詢參數、該次呼叫的選項和一個 `CancellationToken`。請求本文可以是 `System.Text.Json` 能寫出的任何東西：匿名物件、字典、`JsonNode` 或你自己的型別，其屬性名稱會以 snake_case 寫出（`ReplyTo` 變成 `reply_to`）。查詢中的清單以逗號分隔，布林值寫成 `true` 和 `false`，`null` 值會被略過。回應是解析後的 JSON 本文，型別為 `JsonNode?`，使用 API 自己的欄位名稱（`sent?["id"]`），所以 API 參考逐欄位地描述了它；`answer.Deserialize<T>()` 可以把它讀成你自己的型別。

```csharp
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"]}");
}
```

## 冪等與重試

八個傳送操作（`Emails.SendAsync`、`Emails.BatchAsync`、收到的郵件的 `ReplyAsync` 與 `ForwardAsync`、`Inboxes.SendAsync`、`Inboxes.Drafts.SendAsync`、會話串的 `ReplyAsync` 與 `ForwardAsync`）一律會帶上 `Idempotency-Key`。它們的 `IdempotentRequestOptions` 裡沒有 `IdempotencyKey` 時，每次呼叫都會自己產生一個（UUID），並在重試中沿用，所以逾時後的重試不會重複傳送；你自己的鍵還能讓另一個行程中的重複呼叫也保持安全，以同一個鍵和同樣的本文重複呼叫，會回傳第一次的回應。

值得重試的失敗預設會重試兩次：429、5xx、逾時、網路錯誤，以及同一個鍵的第一次請求仍在執行時回傳的 `409 concurrent_idempotent_requests`。只有重複執行也安全的請求才會重試：`GET`、`PUT`、`DELETE` 和傳送操作。用戶端依 `Retry-After`（秒數或 HTTP 日期）的要求等待，要求超過一分鐘時則立即拋出錯誤；其餘情況從 0.5 秒到 8 秒採指數退避，並加上抖動。`MaxRetries` 和 `Timeout` 設定在用戶端上，也可以在單次呼叫的選項中覆寫（`new IdempotentRequestOptions { MaxRetries = 0 }`）；事件串流只在開啟之前計時。

## 錯誤

失敗的呼叫會拋出 `ValidationException`（400、422）、`AuthenticationException`（401，或沒有設定金鑰，此時在任何東西送出之前 `Name` 就會設為 `missing_api_key`）、`PermissionDeniedException`（403）、`NotFoundException`（404）、`ConflictException`（409）、`RateLimitException`（429，`RetryAfter` 以秒為單位）、`ApiException`（5xx）、`ApiConnectionException`（沒有回應：DNS、連線或 TLS 失敗）或 `ApiTimeoutException`（這次嘗試逾時，是 `ApiConnectionException` 的一種）。它們都位於 `BillionSend` 命名空間，並繼承 `BillionSendException`；其他任何狀態則直接拋出 `BillionSendException` 本身。每個都帶有 `StatusCode`（沒有回應時為 `null`）、`Name`（API 的錯誤名稱）、`Message` 和 `RequestId`；`RequestId` 是回應的 `x-request-id`，也就是這個請求在控制台日誌頁面上的 id。取消 `CancellationToken` 會拋出 `OperationCanceledException`，與 .NET 中其他地方一樣。

```csharp
try
{
    var email = await client.Emails.GetAsync(id);
}
catch (NotFoundException)
{
    // 沒有這封郵件
}
catch (BillionSendException error)
{
    Console.WriteLine($"{error.StatusCode} {error.Name}: {error.Message} (request {error.RequestId})");
    throw;
}
```

## 列表

列表方法回傳一頁。每個游標式列表還有一個 `ListAllAsync` 方法（會話串搜尋是 `SearchAllAsync`），回傳 `IAsyncEnumerable<JsonNode>`，會在你讀取時取得後續的頁面，設定了 `before` 時則向前取得：

```csharp
await foreach (var contact in client.Contacts.ListAllAsync(new Dictionary<string, object?> { ["limit"] = 100 }))
{
    Console.WriteLine(contact["email"]);
}
```

## Agent 的收件匣

在[事件串流](/docs/zh-hant/inboxes)上等待新郵件，並在它所在的會話串中回覆：

```csharp
const string inboxId = "support@acme.dev"; // 收件匣的 id 或它的地址

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; // 事件可能有遺漏：重新讀取會話串
    }

    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` 會在串流開啟後回傳，或拋出拒絕它的錯誤，並給出一個 `EventStream`，用 `await foreach` 讀取。`InboxStreamEvent` 有 `Id`、`Event`（Webhook 事件名稱，例如 `inbox.email.received`）、`Data`（Webhook 負載的 `type`、`created_at`、`inbox_id` 和 `data`）以及 `Payload`，也就是內層的 `data`，其中有接下來要讀取的 id。連線中斷時，事件串流會帶著 `Last-Event-ID` 重新連線，並補上錯過的事件；保留 `stream.LastEventId`，並在 `new EventStreamOptions { ... }` 中以 `LastEventId` 傳回去，就能在重新啟動後接續。從 24 小時前的位置恢復時，會收到一次 `StreamGapEvent`。`MaxReconnects`（預設連續失敗 5 次重新連線）可調整重新連線的行為，每次嘗試之前會等待一秒，或伺服器的 `retry` 欄位要求的時間；超過次數後，事件串流會拋出 `ApiConnectionException`。單一收件匣的事件串流在該收件匣被刪除或到期後結束；`client.Inboxes.Events.StreamAsync` 會追蹤金鑰能讀取的所有收件匣。離開迴圈、呼叫 `Close()` 或釋放事件串流，都會讓它安靜地結束，而取消 token 會拋出 `OperationCanceledException`。

## 驗證 Webhook

`Webhook.Verify` 用端點的 `whsec_` 金鑰檢查一次 [Webhook](/docs/zh-hant/concepts/webhooks) 投遞的簽章和時間戳記，並回傳解析後的事件，型別為 `JsonNode`。傳入的請求本文必須與收到時完全一致；標頭可以是一個查詢函式（如下所示）、一個字典，或任何由名稱和值組成的序列，名稱不分大小寫：

```csharp
// 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();
    }
});
```

超過五分鐘的投遞會被拒絕（可用 `WebhookVerifyOptions` 中的 `Tolerance` 調整），金鑰輪替期間，新舊兩個金鑰都能通過驗證。
