如何在 GitHub Actions 中测试邮件

· 5 分钟阅读 · QuickInbox 团队

  • GitHub Actions
  • CI
  • 邮件测试

只在本地运行的邮件测试会错过最关键的时刻:有人在拉取请求中修改了模板或邮件设置。

免费 API 还是 Business API?

免费 API 适合少量测试,但 GitHub 运行器共用 IP 地址,而免费 API 每个 IP 每分钟大约只能创建 10 个新地址。对于 CI,Business API 的私有邮箱更可靠:任何 namespace.tag@quickinbox.net 无需创建调用即可使用,而且只有你的密钥能读取。

第 1 步:密钥

在 Settings > Secrets and variables > Actions 中添加 QI_KEY(为 CI 生成的密钥)和 QI_NAMESPACE。

第 2 步:辅助函数

// inbox.js - private test inboxes with the Business API (Node 18+)
const BASE = 'https://business.quickinbox.net';
const NS = process.env.QI_NAMESPACE;            // e.g. "acme7x"
const auth = { headers: { 'X-API-Key': process.env.QI_KEY } };

// Any tag works at once: acme7x.<tag>@quickinbox.net
export function newAddress(prefix = 'test') {
  const tag = `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
  return { tag, address: `${NS}.${tag}@quickinbox.net` };
}

export async function waitForEmail(tag, { timeoutMs = 60_000, subject = '' } = {}) {
  const since = Math.floor(Date.now() / 1000) - 60;
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const res = await fetch(`${BASE}/api/business/mail?namespace=${NS}&since=${since}&limit=50`, auth);
    if (res.ok) {
      const { messages } = await res.json();
      const hit = messages.find((m) => m.to === `${NS}.${tag}` && m.subject.includes(subject));
      if (hit) return hit; // id, to, from, subject, text, html, spam, receivedAt
    }
    await new Promise((r) => setTimeout(r, 2000));
  }
  throw new Error(`No email for ${tag} within ${timeoutMs} ms`);
}

第 3 步:工作流

# .github/workflows/e2e.yml
name: e2e
on: [pull_request]
jobs:
  e2e:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test
        env:
          QI_KEY: ${{ secrets.QI_KEY }}
          QI_NAMESPACE: ${{ secrets.QI_NAMESPACE }}
          BASE_URL: https://staging.example.com
      - uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: playwright-report
          path: playwright-report

小技巧

  • 把运行 id 放进标签(newAddress(`pr-${process.env.GITHUB_RUN_ID}`)),这样能在工作区中找到某次运行的邮件。
  • 如果邮件测试很多,用 webhook 或实时流代替轮询。参见通过 webhook 接收邮件。
  • 把 CI 命名空间的保留时间设为几天,旧的测试邮件会自动清除。

相关指南

获取私有邮箱:QuickInbox Business API 提供每月 5,000 封邮件的免费套餐,付费套餐每月 $9 起。创建免费账户或阅读 API 文档。

← 全部文章