mcpField
S
smtp2go-api

smtp2go-api

github.com/jezwebその他1.1k110 回インストール3 週間前に更新
リポジトリ

smtp2go-api について

アプリケーションからトランザクションメールやSMSを送信するための、SMTP2GO v3 API連携ガイドです。テンプレート、添付ファイル、Webhook、アクティビティ検索、抑制リスト、配信統計も扱います。

主な機能

  1. 01トランザクションメールとSMSの送信
  2. 02MIMEメールとファイル添付
  3. 03テンプレートの作成と送信
  4. 04配信イベントのWebhook
  5. 05アクティビティ検索と配信統計

活用シーン

  1. 01アプリケーションからトランザクションメールを送信
  2. 02SMTP2GO経由でSMSを配信
  3. 03配信、バウンス、反応イベントを受信
  4. 04配信状況とメール統計を確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/jezweb/claude-skills --skill smtp2go-api

インストール後、Claude Code で/smtp2go-apiを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

README.md
.claude-plugin/
plugin.json
references/
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
EUhttps://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/addPOST新しいテンプレートを作成
/template/editPOST既存のテンプレートを更新
/template/deletePOSTテンプレートを削除
/template/searchPOSTテンプレートを一覧表示/検索
/template/viewPOSTテンプレートの詳細を取得

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/viewPOSTWebhook を一覧表示
/webhook/addPOSTWebhook を作成
/webhook/editPOSTWebhook を更新
/webhook/removePOSTWebhook を削除

再試行ポリシー: 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_summaryPOST統計情報の概要
/stats/email_bouncesPOSTバウンスの概要(30 日間)
/stats/email_cyclePOSTメールサイクルのデータ
/stats/email_historyPOST履歴データ
/stats/email_spamPOSTスパムの報告
/stats/email_unsubsPOST購読解除のデータ

アクティビティ検索

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/addPOST抑制リストに追加
/suppression/viewPOST抑制リストを表示
/suppression/removePOSTリストから削除

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/sendPOSTSMS を送信
/sms/receivedPOST受信した SMS を表示
/sms/sentPOST送信した SMS を表示
/sms/summaryPOSTSMS の統計

レスポンスコード

コードステータス説明
200OK成功
400Bad Requestパラメーターが無効です
401UnauthorizedAPI キーが無効、または指定されていません
402Request Failedパラメーターは有効ですが、リクエストに失敗しました
403Forbidden権限が不足しています
404Not Foundリソースが見つかりません
429Too Many Requestsレート制限に達しました
5xxServer ErrorSMTP2GO サーバーの問題
エラーレスポンスの形式
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;
}

送信者の確認

送信する前に、送信者の本人確認を行ってください。

  1. 送信者ドメイン(推奨): SMTP2GO ダッシュボードでドメインを追加して確認し、SPF/DKIM の整合性を確保します
  2. 単一の送信者メールアドレス: 個別のメールアドレスを確認します

未確認の送信者は 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} &lt;${email}&gt;</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 UnauthorizedAPI キーが未指定、または無効ですヘッダーまたは本文の API キーを確認してください
400 sender not verified送信者ドメインが未確認ですSMTP2GO ダッシュボードでドメインを確認してください
429 Too Many Requestsレート制限を超過しました指数バックオフを実装してください
添付ファイルが大きすぎます合計サイズが 50MB を超えています圧縮するか、URL 参照を使用してください
テンプレート変数が置換されません構文が間違っていますHandlebars 構文 {{ variable }} を使用してください
Webhook がイベントを受信しませんタイムアウト/エラーエンドポイントが 10 秒以内に 200 を返すことを確認してください

参考資料


最終更新日: 2026-02-06 API バージョン: v3.0.3

コメント