在 Node.js 裡用程式接收 email
更新於
在 Node.js 裡接收 email,通常意味著要跑一台 SMTP/IMAP 伺服器,或接上 Gmail 的 API。但對測試、自動化與大多數應用程式流程來說,有條更簡單的路:一個你透過 HTTP 對話的拋棄式收件匣 API。本文是開發者 email 測試的一部分。
兩種接收方式
要嘛輪詢收件匣抓新訊息,要嘛註冊一個 webhook、讓服務把每則訊息推給你。輪詢最容易上手;論延遲與規模,webhook 更好(見進站郵件 webhook)。
建立並輪詢(fetch)
const API = 'https://moemail.app/api'
const H = { 'X-API-Key': process.env.MAIL_KEY }
async function createInbox() {
// expiryTime is milliseconds. Omit `name` for a random address.
const res = await fetch(API + '/emails/generate', {
method: 'POST',
headers: { ...H, 'Content-Type': 'application/json' },
body: JSON.stringify({ expiryTime: 3600000, domain: 'moemail.app' }),
})
return res.json() // { id, email }
}
async function readLatest(id) {
const res = await fetch(API + '/emails/' + id, { headers: H })
const data = await res.json()
return data.messages[0] // newest first
}
Node 18+ 內建 fetch。用短暫延遲反覆呼叫 readLatest,直到有訊息出現,再去讀 .content / .html。
或者接 webhook(Express)
import express from 'express'
const app = express()
app.use(express.json())
app.post('/inbound', (req, res) => {
const mail = req.body // verify the signature first in production
console.log('got mail for', mail.toAddress, '-', mail.subject)
res.sendStatus(200) // respond fast; non-2xx triggers retries
})
app.listen(3000)
handler 要快、要冪等。同一組基本操作也撐起了 Playwright 測試與 Python 版本,在 CI 裡也原封不動就能跑。
開始動手
到個人頁面拿一把金鑰、讀讀 OpenAPI 文件,再建立一個信箱試試看。