---
title: SDK
description: 适用于 Node.js、Python、Go、Ruby、PHP、Rust、Java、.NET 和 Elixir 的 BillionSend SDK，以及供其他语言使用的 REST API。
seo:
  title: 邮件发送 API SDK
ai:
  exclude: true
---

BillionSend 自家的 SDK 覆盖 [API 参考](/docs/zh-hans/api-reference)里的每个端点，包括收信和收件箱。每个 SDK 都从 `BILLIONSEND_API_KEY` 读取 API 密钥，设置了 `BILLIONSEND_BASE_URL` 时也会读取 API 地址，默认是 `https://api.billionsend.com`。

| 语言 | 软件包 | 安装 |
| --- | --- | --- |
| Node.js | [`@billionsend/node`](/docs/zh-hans/sdks/node) 0.1.1 | `npm install @billionsend/node` |
| Python | [`billionsend`](/docs/zh-hans/sdks/python) 0.1.1 | `pip install billionsend` |
| Go | [`github.com/billionsend/billionsend-go`](/docs/zh-hans/sdks/go) 0.1.3 | `go get github.com/billionsend/billionsend-go@v0.1.3` |
| Ruby | [`billionsend`](/docs/zh-hans/sdks/ruby) 0.1.0 | `gem install billionsend` |
| PHP | [`billionsend/billionsend-php`](/docs/zh-hans/sdks/php) 0.1.2 | `composer require billionsend/billionsend-php:^0.1` |
| Rust | [`billionsend`](/docs/zh-hans/sdks/rust) 0.1.2 | `cargo add billionsend@0.1.2` |
| Java | [`com.billionsend:billionsend-java`](/docs/zh-hans/sdks/java) 0.1.2 | `implementation("com.billionsend:billionsend-java:0.1.2")` |
| .NET | [`BillionSend`](/docs/zh-hans/sdks/dotnet) 0.1.0 | `dotnet add package BillionSend --version 0.1.0` |
| Elixir | [`billionsend`](/docs/zh-hans/sdks/elixir) 0.1.0 | `{:billionsend, "~> 0.1"}`（写在 `mix.exs` 里） |

```sh
export BILLIONSEND_API_KEY=bs_...
```

## Node.js / TypeScript

需要 Node 18 或更高版本。

```sh
npm install @billionsend/node
```

```ts
import { BillionSend } from "@billionsend/node";

const bs = new BillionSend(); // 读取 BILLIONSEND_API_KEY

const { data, error } = await bs.emails.send({
  from: "Acme <onboarding@acme.dev>",
  to: ["success@simulator.amazonses.com"],
  subject: "Hello from BillionSend",
  html: "<strong>It works!</strong>",
});

if (error) console.error(error.statusCode, error.name, error.message);
else console.log("sent", data.id);
```

方法从不抛出异常：每次调用都返回 `{ data, error, headers }`。请求字段沿用 API 的名称（`reply_to`、`scheduled_at`）。重试、幂等键、收件箱事件和 Webhook 验签见 [Node.js SDK](/docs/zh-hans/sdks/node) 页面。

## Python

需要 Python 3.11 或更高版本。

```sh
pip install billionsend
```

```python
from billionsend import BillionSend

client = BillionSend()  # 读取 BILLIONSEND_API_KEY

email = client.emails.send(
    {
        "from": "Acme <onboarding@acme.dev>",
        "to": ["success@simulator.amazonses.com"],
        "subject": "Hello from BillionSend",
        "html": "<strong>It works!</strong>",
    }
)
print(email["id"])
```

调用失败时会抛出 `BillionSendError` 的子类。`AsyncBillionSend` 为 `asyncio` 提供同样的方法。更多内容见 [Python SDK](/docs/zh-hans/sdks/python) 页面。

## Go

需要 Go 1.23 或更高版本。

```sh
go get github.com/billionsend/billionsend-go
```

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/billionsend/billionsend-go"
)

func main() {
	ctx := context.Background()
	client := billionsend.NewClient() // 读取 BILLIONSEND_API_KEY

	sent, err := client.Emails.Send(ctx, &billionsend.SendEmailRequest{
		From:    "Acme <onboarding@acme.dev>",
		To:      []string{"success@simulator.amazonses.com"},
		Subject: "Hello from BillionSend",
		HTML:    billionsend.String("<strong>It works!</strong>"),
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("sent", sent.ID)
}
```

调用失败时返回的错误可以解包为 `*billionsend.Error`。可选字段是指针（`billionsend.String`、`Int64`、`Bool`）。更多内容见 [Go SDK](/docs/zh-hans/sdks/go) 页面。

## Ruby

需要 Ruby 3.1 或更高版本。

```sh
gem install billionsend
```

```ruby
require "billionsend"

client = BillionSend::Client.new # 读取 BILLIONSEND_API_KEY

sent = client.emails.send({
  from: "Acme <onboarding@acme.dev>",
  to: ["success@simulator.amazonses.com"],
  subject: "Hello from BillionSend",
  html: "<strong>It works!</strong>"
})
puts "sent #{sent["id"]}"
```

返回值是键为字符串、字段名与 API 一致的 Hash（`sent["id"]`），调用失败时抛出 `BillionSend::Error` 的子类。更多内容见 [Ruby SDK](/docs/zh-hans/sdks/ruby) 页面。

## PHP

需要 PHP 8.1 或更高版本。

```sh
composer require billionsend/billionsend-php:^0.1
```

```php
use BillionSend\Client;

$client = new Client(); // 读取 BILLIONSEND_API_KEY

$sent = $client->emails->send([
    'from' => 'Acme <onboarding@acme.dev>',
    'to' => ['success@simulator.amazonses.com'],
    'subject' => 'Hello from BillionSend',
    'html' => '<strong>It works!</strong>',
]);
echo 'sent ', $sent['id'], "\n";
```

请求体和返回值都是字段名与 API 一致的关联数组，调用失败时抛出 `BillionSendError` 的子类。更多内容见 [PHP SDK](/docs/zh-hans/sdks/php) 页面。

## Rust

需要 Rust 1.85 或更高版本，并搭配 `tokio`。

```sh
cargo add billionsend serde_json
cargo add tokio --features macros,rt-multi-thread
```

```rust
use billionsend::BillionSend;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), billionsend::Error> {
    let bs = BillionSend::from_env(); // 读取 BILLIONSEND_API_KEY

    let sent = bs
        .emails()
        .send(&json!({
            "from": "Acme <onboarding@acme.dev>",
            "to": ["success@simulator.amazonses.com"],
            "subject": "Hello from BillionSend",
            "html": "<strong>It works!</strong>",
        }))
        .await?;
    println!("sent {}", sent["id"].as_str().unwrap_or_default());
    Ok(())
}
```

调用失败时返回 `billionsend::Error`，每种错误对应一个变体（`NotFound`、`RateLimit` 等）。请求体可以是任何 `serde::Serialize` 的值，例如 `json!`；返回值是 `serde_json::Value`，也可以用 `.json::<T>()` 读成你自己的类型。更多内容见 [Rust SDK](/docs/zh-hans/sdks/rust) 页面。

## Java

需要 Java 17 或更高版本。用 Gradle 的写法如下（Maven：`com.billionsend:billionsend-java:0.1.2`）：

```kotlin
implementation("com.billionsend:billionsend-java:0.1.2")
```

```java
import com.billionsend.BillionSend;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import java.util.Map;

public class Hello {
  public static void main(String[] args) {
    BillionSend client = new BillionSend(); // 读取 BILLIONSEND_API_KEY

    JsonNode sent =
        client.emails().send(
            Map.of(
                "from", "Acme <onboarding@acme.dev>",
                "to", List.of("success@simulator.amazonses.com"),
                "subject", "Hello from BillionSend",
                "html", "<strong>It works!</strong>"));
    System.out.println("sent " + sent.get("id").asText());
  }
}
```

调用失败时抛出非受检的 `BillionSendException` 子类。请求体可以是 Jackson 能写出的任何值，例如字段名与 API 一致的 `Map`；返回值是 `JsonNode` 树。更多内容见 [Java SDK](/docs/zh-hans/sdks/java) 页面。

## .NET

需要 .NET 8 或更高版本。

```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 <onboarding@acme.dev>",
    to = new[] { "success@simulator.amazonses.com" },
    subject = "Hello from BillionSend",
    html = "<strong>It works!</strong>",
});
Console.WriteLine($"sent {sent?["id"]}");
```

方法是异步的（`SendAsync`），返回值是字段名与 API 一致的 `JsonNode` 树。调用失败时抛出 `BillionSendException` 的子类。更多内容见 [.NET SDK](/docs/zh-hans/sdks/dotnet) 页面。

## Elixir

需要 Elixir 1.18 或更高版本，以及 OTP 25 或更高版本。写在 `mix.exs` 里：

```elixir
def deps do
  [{:billionsend, "~> 0.1"}]
end
```

```elixir
client = BillionSend.client()  # 读取 BILLIONSEND_API_KEY

{:ok, sent} =
  BillionSend.Emails.send(client, %{
    from: "Acme <onboarding@acme.dev>",
    to: ["success@simulator.amazonses.com"],
    subject: "Hello from BillionSend",
    html: "<strong>It works!</strong>"
  })

IO.puts("sent #{sent["id"]}")
```

每个函数都返回 `{:ok, answer}` 或 `{:error, error}`，带 `!` 的同名函数则在失败时抛出异常。返回值是键为字符串、字段名与 API 一致的 map。更多内容见 [Elixir SDK](/docs/zh-hans/sdks/elixir) 页面。

## 其他语言：cURL

用其他任何语言时，都可以用任意 HTTP 客户端和同一个密钥调用 REST API：

```sh
curl -X POST "https://api.billionsend.com/emails" \
  -H "Authorization: Bearer $BILLIONSEND_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: welcome/ana" \
  -d '{
    "from": "Acme <onboarding@acme.dev>",
    "to": ["success@simulator.amazonses.com"],
    "subject": "Hello from BillionSend",
    "html": "<strong>It works!</strong>"
  }'
```

返回值是 `{ "id": "..." }`。带上 `Idempotency-Key` 后，超时重试就是安全的：用同一个键和同一个请求体重复请求，会返回第一次的结果，不会再发一次。认证、错误、限额和分页见 [API 基础](/docs/zh-hans/api-reference/basics)，每个端点及其字段见 [API 参考](/docs/zh-hans/api-reference)。

## 命令行

[`@billionsend/cli`](/docs/zh-hans/cli) 0.2.5 可以把账号从其他服务商迁到 BillionSend。它是迁移工具，不是发送客户端。
