mcpField
S
smtp2go-api

smtp2go-api

github.com/jezweb其他1.1k110 次安装3 周前更新
代码仓库

关于 smtp2go-api

面向开发者的 SMTP2GO v3 API 集成指南,用于在应用中发送事务性邮件和 SMS。还介绍模板、附件、Webhook、活动搜索、抑制列表及投递统计。

主要功能

  1. 01发送事务性邮件和 SMS
  2. 02MIME 邮件与文件附件
  3. 03创建和发送模板邮件
  4. 04投递事件 Webhook
  5. 05活动搜索与投递统计

适用场景

  1. 01从应用发送事务性邮件
  2. 02通过 SMTP2GO 发送 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
欧洲https://eu-api.smtp2go.com/v3
澳大利亚https://au-api.smtp2go.com/v3

身份验证

支持两种方法:

// 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
})

从 SMTP2GO 控制面板获取 API 密钥: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/viewPOST列出 Webhook
/webhook/addPOST创建 Webhook
/webhook/editPOST更新 Webhook
/webhook/removePOST删除 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_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/sendPOST发送 SMS
/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 引用
模板变量未替换语法错误使用 {{ variable }} Handlebars 语法
Webhook 未收到事件超时或错误检查端点是否在 10s 内返回 200

参考资料


最后更新: 2026-02-06 API 版本: v3.0.3

评论

支持 Markdown