smtp2go-api について
アプリケーションからトランザクションメールやSMSを送信するための、SMTP2GO v3 API連携ガイドです。テンプレート、添付ファイル、Webhook、アクティビティ検索、抑制リスト、配信統計も扱います。
主な機能
- 01トランザクションメールとSMSの送信
- 02MIMEメールとファイル添付
- 03テンプレートの作成と送信
- 04配信イベントのWebhook
- 05アクティビティ検索と配信統計
活用シーン
- 01アプリケーションからトランザクションメールを送信
- 02SMTP2GO経由でSMSを配信
- 03配信、バウンス、反応イベントを受信
- 04配信状況とメール統計を確認
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ jezweb/ claude-skills --skill smtp2go-apiインストール後、Claude Code で/smtp2go-apiを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
README.md.claude-plugin/plugin.jsonreferences/endpoints.md詳細
SMTP2GO API 連携
SMTP2GO トランザクション API を使用して、メールと SMS の配信を構築します。
クイックスタート
// Send email with SMTP2GO
const response = await fetch('https://api.smtp2go.com/v3/email/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
sender: '[email protected]',
to: ['[email protected]'],
subject: 'Hello from SMTP2GO',
html_body: '<h1>Welcome!</h1><p>Your account is ready.</p>',
text_body: 'Welcome! Your account is ready.',
}),
});
const result = await response.json();
// { request_id: "uuid", data: { succeeded: 1, failed: 0, email_id: "1er8bV-6Tw0Mi-7h" } }
ベース URL
| リージョン | ベース URL |
|---|---|
| グローバル | https://api.smtp2go.com/v3 |
| 米国 | https://us-api.smtp2go.com/v3 |
| EU | https://eu-api.smtp2go.com/v3 |
| オーストラリア | https://au-api.smtp2go.com/v3 |
認証
次の 2 つの方法がサポートされています。
// Method 1: Header (recommended)
headers: {
'X-Smtp2go-Api-Key': 'your-api-key'
}
// Method 2: Request body
body: JSON.stringify({
api_key: 'your-api-key',
// ... other params
})
API キーは SMTP2GO ダッシュボードの Sending > API Keys から取得できます。
主要なエンドポイント
標準メールを送信
POST /email/send
interface EmailSendRequest {
// Required
sender: string; // Verified sender email
to: string[]; // Recipients (max 100)
subject: string;
// Content (at least one required)
html_body?: string;
text_body?: string;
// Optional
cc?: string[]; // CC recipients (max 100)
bcc?: string[]; // BCC recipients (max 100)
reply_to?: string;
custom_headers?: Array<{ header: string; value: string }>;
attachments?: Attachment[];
inlines?: InlineImage[];
// Templates
template_id?: string;
template_data?: Record<string, any>;
// Subaccounts
subaccount_id?: string;
}
interface Attachment {
filename: string;
mimetype: string;
fileblob?: string; // Base64-encoded content
url?: string; // OR URL to fetch from
}
interface InlineImage {
filename: string;
mimetype: string;
fileblob: string;
cid: string; // Content-ID for HTML reference
}
レスポンス:
interface EmailSendResponse {
request_id: string;
data: {
succeeded: number;
failed: number;
failures: string[];
email_id: string;
};
}
MIME メールを送信
POST /email/mime
エンコード済みの MIME メッセージの場合:
const response = await fetch('https://api.smtp2go.com/v3/email/mime', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
mime_email: mimeEncodedString,
}),
});
添付ファイル
Base64 エンコード
// Convert file to base64
const fileBuffer = await file.arrayBuffer();
const base64 = btoa(String.fromCharCode(...new Uint8Array(fileBuffer)));
const email = {
sender: '[email protected]',
to: ['[email protected]'],
subject: 'Document attached',
text_body: 'Please find the document attached.',
attachments: [{
filename: 'report.pdf',
fileblob: base64,
mimetype: 'application/pdf',
}],
};
URL 参照(24 時間キャッシュ)
const email = {
sender: '[email protected]',
to: ['[email protected]'],
subject: 'Image attached',
text_body: 'Photo from our event.',
attachments: [{
filename: 'photo.jpg',
url: 'https://cdn.example.com/photos/event.jpg',
mimetype: 'image/jpeg',
}],
};
HTML 内のインライン画像
const email = {
sender: '[email protected]',
to: ['[email protected]'],
subject: 'Newsletter',
html_body: '<h1>Welcome</h1><img src="cid:logo123" alt="Logo">',
inlines: [{
filename: 'logo.png',
fileblob: logoBase64,
mimetype: 'image/png',
cid: 'logo123', // Reference in HTML as src="cid:logo123"
}],
};
制限: メールの合計サイズは最大 50 MB です(コンテンツ + 添付ファイル + ヘッダー)。
テンプレート
テンプレートを作成
POST /template/add
const response = await fetch('https://api.smtp2go.com/v3/template/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
template_name: 'welcome-email',
html_body: '<h1>Welcome, {{ name }}!</h1><p>Thanks for joining {{ company }}.</p>',
text_body: 'Welcome, {{ name }}! Thanks for joining {{ company }}.',
}),
});
テンプレートを使用して送信
const email = {
sender: '[email protected]',
to: ['[email protected]'],
subject: 'Welcome aboard!',
template_id: 'template-uuid-here',
template_data: {
name: 'John',
company: 'Acme Corp',
},
};
テンプレート構文: {{ variable }} プレースホルダーを使った HandlebarsJS です。
テンプレートのエンドポイント
| エンドポイント | メソッド | 説明 |
|---|---|---|
/template/add | POST | 新しいテンプレートを作成 |
/template/edit | POST | 既存のテンプレートを更新 |
/template/delete | POST | テンプレートを削除 |
/template/search | POST | テンプレートを一覧表示/検索 |
/template/view | POST | テンプレートの詳細を取得 |
Webhook
Webhook を設定して、配信通知をリアルタイムで受け取ります。
イベントの種類
メールイベント:
| イベント | 説明 |
|---|---|
processed | メールが配信待ちに追加されました |
delivered | 正常に配信されました |
open | 受信者がメールを開封しました |
click | リンクがクリックされました |
bounce | 配信に失敗しました |
spam | スパムとしてマークされました |
unsubscribe | ユーザーが購読を解除しました |
resubscribe | ユーザーが再購読しました |
reject | ブロックされました(抑制/サンドボックス) |
SMS イベント:
| イベント | 説明 |
|---|---|
sending | 処理中 |
submitted | プロバイダーに送信されました |
delivered | 配信が確認されました |
failed | 配信に失敗しました |
rejected | ネットワークによってブロックされました |
opt-out | 受信者が配信停止を選択しました |
Webhook ペイロード(メール)
interface WebhookPayload {
event: string;
time: string; // Event timestamp
sendtime: string; // Original send time
sender: string;
from_address: string;
rcpt: string; // Recipient
recipients: string[];
email_id: string;
subject: string;
bounce?: string; // Bounce type if applicable
client?: string; // Email client (for opens)
'geoip-country'?: string;
}
Webhook の設定
POST /webhook/add
await fetch('https://api.smtp2go.com/v3/webhook/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
url: 'https://api.yourdomain.com/webhooks/smtp2go',
events: ['delivered', 'bounce', 'spam', 'unsubscribe'],
}),
});
Webhook のエンドポイント
| エンドポイント | メソッド | 説明 |
|---|---|---|
/webhook/view | POST | Webhook を一覧表示 |
/webhook/add | POST | Webhook を作成 |
/webhook/edit | POST | Webhook を更新 |
/webhook/remove | POST | Webhook を削除 |
再試行ポリシー: 48 時間にわたり最大 35 回再試行します。タイムアウト:10 秒。
統計
メールの概要
POST /stats/email_summary
バウンス、サイクル、スパム、購読解除をまとめたレポートです。
const response = await fetch('https://api.smtp2go.com/v3/stats/email_summary', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({}),
});
統計エンドポイント
| エンドポイント | メソッド | 説明 |
|---|---|---|
/stats/email_summary | POST | 統計情報の概要 |
/stats/email_bounces | POST | バウンスの概要(30 日間) |
/stats/email_cycle | POST | メールサイクルのデータ |
/stats/email_history | POST | 履歴データ |
/stats/email_spam | POST | スパムの報告 |
/stats/email_unsubs | POST | 購読解除のデータ |
アクティビティ検索
POST /activity/search(レート制限:60 回/分)
メールイベントを検索します:
const response = await fetch('https://api.smtp2go.com/v3/activity/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
// Filter parameters
}),
});
注: 返される項目は最大 1,000 件です。リアルタイムのデータには、代わりに Webhook を使用してください。
抑制リスト
メールを送信しないアドレスを管理します。
抑制リストに追加
POST /suppression/add
await fetch('https://api.smtp2go.com/v3/suppression/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
email: '[email protected]',
}),
});
抑制リストのエンドポイント
| エンドポイント | メソッド | 説明 |
|---|---|---|
/suppression/add | POST | 抑制リストに追加 |
/suppression/view | POST | 抑制リストを表示 |
/suppression/remove | POST | リストから削除 |
SMS
POST /sms/send
const response = await fetch('https://api.smtp2go.com/v3/sms/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
to: ['+61400000000'], // Max 100 numbers
message: 'Your verification code is 123456',
}),
});
SMS エンドポイント
| エンドポイント | メソッド | 説明 |
|---|---|---|
/sms/send | POST | SMS を送信 |
/sms/received | POST | 受信した SMS を表示 |
/sms/sent | POST | 送信した SMS を表示 |
/sms/summary | POST | SMS の統計 |
レスポンスコード
| コード | ステータス | 説明 |
|---|---|---|
| 200 | OK | 成功 |
| 400 | Bad Request | パラメーターが無効です |
| 401 | Unauthorized | API キーが無効、または指定されていません |
| 402 | Request Failed | パラメーターは有効ですが、リクエストに失敗しました |
| 403 | Forbidden | 権限が不足しています |
| 404 | Not Found | リソースが見つかりません |
| 429 | Too Many Requests | レート制限に達しました |
| 5xx | Server Error | SMTP2GO サーバーの問題 |
エラーレスポンスの形式
interface ErrorResponse {
request_id: string;
data: {
error: string;
error_code: string;
field_validation_errors?: Record<string, string>;
};
}
一般的なエラーコード:
E_ApiResponseCodes.ENDPOINT_PERMISSION_DENIED- API キーに権限がありませんE_ApiResponseCodes.NON_VALIDATING_IN_PAYLOAD- JSON/メール形式が無効ですE_ApiResponseCodes.API_EXCEPTION- 一般的な API エラー
レート制限
- アクティビティ検索: 60 リクエスト/分
- メール検索(非推奨): 20 リクエスト/分
- その他のエンドポイント: API キーごとに設定可能
429 への対処:
async function sendWithRetry(payload: any, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const response = await fetch('https://api.smtp2go.com/v3/email/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify(payload),
});
if (response.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
continue;
}
return response.json();
}
throw new Error('Rate limit exceeded after retries');
}
Cloudflare Workers との統合
// wrangler.jsonc
{
"name": "email-service",
"vars": {
"SMTP2GO_REGION": "api" // or "us-api", "eu-api", "au-api"
}
}
// .dev.vars
SMTP2GO_API_KEY=api-XXXXXXXXXXXX
// src/index.ts
export default {
async fetch(request: Request, env: Env) {
const baseUrl = `https://${env.SMTP2GO_REGION}.smtp2go.com/v3`;
// Send transactional email
const response = await fetch(`${baseUrl}/email/send`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
sender: '[email protected]',
to: ['[email protected]'],
subject: 'Order Confirmation',
template_id: 'order-confirmation-template',
template_data: {
order_id: '12345',
total: '$99.00',
},
}),
});
const result = await response.json();
return Response.json(result);
},
} satisfies ExportedHandler<Env>;
interface Env {
SMTP2GO_API_KEY: string;
SMTP2GO_REGION: string;
}
送信者の確認
送信する前に、送信者の本人確認を行ってください。
- 送信者ドメイン(推奨): SMTP2GO ダッシュボードでドメインを追加して確認し、SPF/DKIM の整合性を確保します
- 単一の送信者メールアドレス: 個別のメールアドレスを確認します
未確認の送信者は 400 エラーで拒否されます。
一般的なパターン
お問い合わせフォームのハンドラー
export async function handleContactForm(formData: FormData, env: Env) {
const name = formData.get('name') as string;
const email = formData.get('email') as string;
const message = formData.get('message') as string;
const response = await fetch('https://api.smtp2go.com/v3/email/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Smtp2go-Api-Key': env.SMTP2GO_API_KEY,
},
body: JSON.stringify({
sender: '[email protected]',
to: ['[email protected]'],
reply_to: email,
subject: `Contact form: ${name}`,
text_body: `From: ${name} <${email}>\n\n${message}`,
html_body: `
<p><strong>From:</strong> ${name} <${email}></p>
<hr>
<p>${message.replace(/\n/g, '<br>')}</p>
`,
}),
});
if (!response.ok) {
throw new Error('Failed to send email');
}
return response.json();
}
Webhook ハンドラー
export async function handleWebhook(request: Request) {
const payload = await request.json();
switch (payload.event) {
case 'bounce':
// Handle bounce - update user record, retry logic
console.log(`Bounce: ${payload.rcpt} - ${payload.bounce}`);
break;
case 'unsubscribe':
// Update preferences
console.log(`Unsubscribe: ${payload.rcpt}`);
break;
case 'spam':
// Add to suppression, alert team
console.log(`Spam report: ${payload.rcpt}`);
break;
}
return new Response('OK', { status: 200 });
}
トラブルシューティング
| 問題 | 原因 | 解決策 |
|---|---|---|
| 401 Unauthorized | API キーが未指定、または無効です | ヘッダーまたは本文の API キーを確認してください |
| 400 sender not verified | 送信者ドメインが未確認です | SMTP2GO ダッシュボードでドメインを確認してください |
| 429 Too Many Requests | レート制限を超過しました | 指数バックオフを実装してください |
| 添付ファイルが大きすぎます | 合計サイズが 50MB を超えています | 圧縮するか、URL 参照を使用してください |
| テンプレート変数が置換されません | 構文が間違っています | Handlebars 構文 {{ variable }} を使用してください |
| Webhook がイベントを受信しません | タイムアウト/エラー | エンドポイントが 10 秒以内に 200 を返すことを確認してください |
参考資料
最終更新日: 2026-02-06 API バージョン: v3.0.3