Sendery
Sendery

言語別 SDK

Go

Sendery のテンプレートを使って Go からトランザクションメールを送信します。

インストール
go get github.com/sendery-co/[email protected]
ソースコード

動作環境

Go 1.26 以上が必要です。go.mod があるプロジェクトで SDK をインストールしてください。

送信の準備

name と action_url を使う welcome テンプレートを公開し、プロジェクトの API キーを作成します。サーバーの環境変数 SENDERY_API_KEY に保存してください。

Shell
export SENDERY_API_KEY="your_project_api_key"

メールを送信

受付済みメールの ID と Status が返ります。Locale でテンプレートの言語を指定できます。変数がない場合は Data を省略すると、空の JSON オブジェクトとして送信されます。

Go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/sendery-co/sendery-go"
)

func main() {
	client, err := sendery.NewClient(os.Getenv("SENDERY_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	receipt, err := client.Send(context.Background(), sendery.SendEmailInput{
		To:       "[email protected]",
		Template: "welcome",
		Data: map[string]any{
			"name":       "Alex",
			"action_url": "https://example.com/start",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(receipt.ID)
}

メールを取得

返された ID で配信状態を確認します。

Go
message, err := client.Get(context.Background(), receipt.ID)
if err != nil {
	log.Fatal(err)
}
fmt.Println(message.Status)

送信を再試行

welcome-123 のようなキーをメールごとに用意し、再試行時もキーと内容を変えずに送信します。Prepare は送信内容のコピーを保持します。WithRetries(3) は一時的なエラーで最大 3 回の追加試行を行い、省略時は 1 回のみ試行します。キーは email.IdempotencyKey() で取得できます。

Go
email, err := client.Prepare(sendery.SendEmailInput{
	To:       "[email protected]",
	Template: "welcome",
	Data: map[string]any{
		"name":       "Alex",
		"action_url": "https://example.com/start",
	},
}, sendery.WithIdempotencyKey("welcome-123"), sendery.WithRetries(3))
if err != nil {
	log.Fatal(err)
}

receipt, err := email.Send(context.Background())
if err != nil {
	log.Fatal(err)
}
fmt.Println(receipt.ID)

エラーを処理

errors.As でステータス、コード、項目エラーを確認します。RetryAfter は *time.Duration で、待機時間が指定されていない場合は nil です。以下では再試行の例で作成した email を使用します。

Go
// Add "errors" to your imports.
receipt, err := email.Send(context.Background())
if err != nil {
	var apiError *sendery.APIError
	if errors.As(err, &apiError) {
		log.Printf("%d: %s", apiError.Status, apiError.Code)
		for field, messages := range apiError.Errors {
			log.Printf("%s: %v", field, messages)
		}
		if apiError.RetryAfter != nil {
			log.Printf("Retry after %s", *apiError.RetryAfter)
		}
	}
	log.Fatal(err)
}
fmt.Println(receipt.ID)

タイムアウトを設定

Send や Get にコンテキストを渡すと、リクエストのキャンセルや実行時間の制限ができます。HTTP タイムアウトの既定値は 1 回の試行につき 10 秒です。コンテキストの期限は再試行の待機中も適用されます。キャンセル時は context.Canceled または context.DeadlineExceeded が返ります。メールが受付済みの可能性があるため、再送する場合は同じキーと内容を使ってください。

Go
// Add "time" to your imports. In an HTTP handler, use r.Context()
// as the parent context so requests stop when the caller disconnects.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

receipt, err := email.Send(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(receipt.ID)