跳到内容
Esc
↑↓导航↵打开⌘J预览
本页内容

SDK

適用於 Node.js、Python、Go、Ruby、PHP、Rust、Java、.NET 與 Elixir 的 BillionSend SDK,以及供其他語言使用的 REST API。

BillionSend 自家的 SDK 涵蓋 API 參考裡的每個端點,包括收信與收件匣。每個 SDK 都會從 BILLIONSEND_API_KEY 讀取 API 金鑰,有設定 BILLIONSEND_BASE_URL 時也會讀取 API 位址,預設是 https://api.billionsend.com。

語言 套件 安裝
Node.js @billionsend/node 0.1.1 npm install @billionsend/node
Python billionsend 0.1.1 pip install billionsend
Go github.com/billionsend/billionsend-go 0.1.3 go get github.com/billionsend/billionsend-go@v0.1.3
Ruby billionsend 0.1.0 gem install billionsend
PHP billionsend/billionsend-php 0.1.2 composer require billionsend/billionsend-php:^0.1
Rust billionsend 0.1.2 cargo add billionsend@0.1.2
Java com.billionsend:billionsend-java 0.1.2 implementation("com.billionsend:billionsend-java:0.1.2")
.NET BillionSend 0.1.0 dotnet add package BillionSend --version 0.1.0
Elixir billionsend 0.1.0 {:billionsend, "~> 0.1"},寫在 mix.exs 裡
export BILLIONSEND_API_KEY=bs_...

Node.js / TypeScript

需要 Node 18 或更新版本。

npm install @billionsend/node
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 頁面。

Python

需要 Python 3.11 或更新版本。

pip install billionsend
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 頁面。

Go

需要 Go 1.23 或更新版本。

go get github.com/billionsend/billionsend-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 頁面。

Ruby

需要 Ruby 3.1 或更新版本。

gem install billionsend
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 頁面。

PHP

需要 PHP 8.1 或更新版本。

composer require billionsend/billionsend-php:^0.1
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 頁面。

Rust

需要 Rust 1.85 或更新版本,並搭配 tokio。

cargo add billionsend serde_json
cargo add tokio --features macros,rt-multi-thread
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 頁面。

Java

需要 Java 17 或更新版本。用 Gradle 的寫法如下(Maven:com.billionsend:billionsend-java:0.1.2):

implementation("com.billionsend:billionsend-java:0.1.2")
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 頁面。

.NET

需要 .NET 8 或更新版本。

dotnet add package BillionSend --version 0.1.0
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 頁面。

Elixir

需要 Elixir 1.18 或更新版本,以及 OTP 25 或更新版本。寫在 mix.exs 裡:

def deps do
  [{:billionsend, "~> 0.1"}]
end
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 頁面。

其他語言:cURL

用任何其他語言時,以任何 HTTP 用戶端搭配同一把金鑰呼叫 REST API 即可:

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 基礎,每個端點及其欄位都在 API 參考裡。

命令列

@billionsend/cli 0.2.5 可把帳號從其他服務商遷移到 BillionSend。它是遷移工具,不是寄信用的用戶端。

这个页面有帮助吗?