跳至正文
使用场景

临时邮箱 REST API:用密钥读取收件箱与邮件

临时邮箱 REST API 供你的服务端读取获授权的收件箱和邮件。只授予必要权限,把密钥放在服务器上,并以当前文档和限额为准;API 不能打开任意邮箱地址。

本页内容

API 让程序按授权范围调用已开放的功能。密钥不能代替套餐资格,也不授予读取任意邮箱的权力。临时邮箱仍然只接收邮件,换成程序调用并不会取消原有规则。

实用示例:用临时邮箱 API 读取测试邮件

仅将单独管理的 API 密钥用于获授权的收件箱和操作。不要在示例或日志中暴露凭据,并使用非敏感邮件测试。

限制并保护 API 密钥

在规定账户区域创建最小必要权限。将密钥保存在服务端,不放进公开 JavaScript、URL、共享仓库或日志。端点、错误和限流以当前文档为准,概述文章不能替代接口规范。

测试时不要使用客户的机密信息

先用虚构数据检查创建、授权读取和错误处理。到期、保留和套餐限额同样适用于 API。不再使用的密钥请及时撤销,不要把权限被拒当作需要绕过的障碍。排查缺失邮件时,仍要区分发送、邮件服务商投递与平台导入。

一个 API 密钥能打开所有临时邮箱吗?

不能。账户、权限范围和资源授权继续决定访问。

API 密钥可以放在前端代码里吗?

不可以。应远离公开代码和日志。

用临时邮箱 API 接收邮件的代码示例

准备符合条件的收件箱和仅含必要权限的密钥。下面的服务端客户端使用已发布的路径;不要把密钥放进浏览器或公开日志。

// Receive-only example. Keep this module and its token on the Node/server side.
import {setTimeout as sleep} from 'node:timers/promises';

export function createEmailClient({token, base='https://tempmailace.com', intervalMs=2000}) {
  const origin=new URL(base);
  const local=['127.0.0.1','localhost','[::1]'].includes(origin.hostname);
  if (origin.username || origin.password || origin.pathname!=='/' || origin.search || origin.hash ||
      !(origin.origin==='https://tempmailace.com' || (local && origin.protocol==='http:'))) {
    throw new Error('Use the verified production origin or a local contract-test server');
  }
  if (!token) throw new Error('A scoped server-side API token is required');
  const segment=x=>encodeURIComponent(String(x));
  async function get(path, deadline) {
    while(Date.now()<deadline) {
      const response=await fetch(origin.origin+path, {
        headers:{Authorization:`Bearer ${token}`,Accept:'application/json'},
        redirect:'error',signal:AbortSignal.timeout(Math.max(1,Math.min(10000,deadline-Date.now())))
      });
      if (response.status===429) {
        const retry=response.headers.get('retry-after');
        const seconds=retry===null ? NaN : Number(retry);
        const waitMs=Number.isFinite(seconds) ? Math.max(0,seconds*1000) : Math.max(0,Date.parse(retry||'')-Date.now());
        const pause=Math.max(intervalMs,Number.isFinite(waitMs)?waitMs:intervalMs);
        await response.body?.cancel();
        if (Date.now()+pause>=deadline) break;
        await sleep(pause);continue;
      }
      if(!response.ok) {await response.body?.cancel();throw new Error(`Email API HTTP ${response.status}`);}
      return response.json();
    }
    throw new Error('Email wait timed out');
  }
  async function scan(inboxId,deadline) {
    const messages=[];let offset=0;const offsets=new Set();
    for(let page=0;page<100;page++) {
      if(offsets.has(offset)) throw new Error('Repeated pagination offset');
      offsets.add(offset);
      const payload=await get(`/api/developer/v1/inboxes/${segment(inboxId)}/messages?offset=${offset}`,deadline);
      if(!Array.isArray(payload.items) || typeof payload.has_more!=='boolean') throw new Error('Unexpected messages contract');
      messages.push(...payload.items);
      if(!payload.has_more) return messages;
      if(!Number.isInteger(payload.next_offset) || payload.next_offset<=offset) throw new Error('Invalid pagination offset');
      offset=payload.next_offset;
    }
    throw new Error('Pagination budget exceeded; dedicate an inbox to this test');
  }
  return {
    listInboxes:({timeoutMs=15000}={})=>get('/api/developer/v1/inboxes',Date.now()+timeoutMs),
    async waitForMessage({inboxId,subject,sender,since,timeoutMs=60000,excludeIds=[]}) {
      if(!inboxId || !subject || !sender || !Number.isFinite(Date.parse(since))) throw new Error('inboxId, exact subject, exact sender and ISO since are required');
      const deadline=Date.now()+timeoutMs,excluded=new Set(excludeIds),after=Date.parse(since);
      while(Date.now()<deadline) {
        const items=await scan(inboxId,deadline);
        const match=items.find(m=>m.id && !excluded.has(m.id) && m.subject===subject && m.from===sender && Date.parse(m.received_at)>=after);
        if(match) {
          const full=await get(`/api/developer/v1/inboxes/${segment(inboxId)}/messages/${segment(match.id)}`,deadline);
          if(full.id!==match.id || full.subject!==subject || full.from!==sender) throw new Error('Message changed during read');
          return full;
        }
        const remaining=deadline-Date.now();if(remaining<=0)break;
        await sleep(Math.min(intervalMs,remaining));
      }
      throw new Error('Email wait timed out');
    }
  };
}

// This is the exact format of the owned demo application, not a universal OTP parser.
export function demoCode(message) {
  const match=String(message.text||'').match(/Verification code:\s*(\d{6})(?!\d)/);
  if(!match) throw new Error('The demo six-digit code was not found');
  return match[1];
}

// Validate a link before a browser test follows it. Never navigate to arbitrary mail HTML.
export function demoVerificationLink(message, appOrigin) {
  const raw=String(message.text||'').match(/https?:\/\/[^\s<>"']+/)?.[0];
  if(!raw)throw new Error('No demo link');
  const link=new URL(raw),app=new URL(appOrigin);
  if(link.origin!==app.origin || link.pathname!=='/verify-email' || !link.searchParams.get('token') || link.username || link.password)throw new Error('Untrusted verification link');
  return link.href;
}

运行并检查结果

从服务端测试调用客户端,在有限时间内等待目标邮件,再检查发件人和内容。权限错误或收件箱过期应与投递延迟分开处理。

将第一段保存为 email-client.mjs,放在支持 fetch 和 AbortSignal.timeout 的 Node.js 服务端。在服务端或 CI 中设置 TMA_API_KEY、TMA_INBOX_ID、TEST_SUBJECT、TEST_SENDER 和 TEST_SINCE:分别是密钥、收件箱 ID、唯一主题、准确的发件人值,以及发送之前记录的 ISO 时间。先由自己的应用发送测试邮件;此 API 示例只接收邮件,不负责发送。

import {createEmailClient} from './email-client.mjs';

const client = createEmailClient({token: process.env.TMA_API_KEY});
await client.waitForMessage({
  inboxId: process.env.TMA_INBOX_ID,
  subject: process.env.TEST_SUBJECT,
  sender: process.env.TEST_SENDER,
  since: process.env.TEST_SINCE,
  timeoutMs: 60000
});
console.log('The matching test message was read.');

更多临时邮箱 API 指南

延伸阅读:

需要这方面的帮助吗?

联系对应的团队,或查看全部官方联系渠道。