Node SDK
推荐应用优先使用 SDK,而不是手写 HTTP 请求。包名 @wydev/amail,当前版本 1.3.0。
安装:
bash
npm install @wydev/amail创建客户端:
ts
import { Amail } from '@wydev/amail'
const amail = new Amail('am_your_api_key', {
baseUrl: 'https://mail.example.com',
})key:也可读环境变量AMAIL_API_KEYoptions.baseUrl:服务地址,默认http://localhost:3000,也可读AMAIL_BASE_URLoptions.providerId:默认通道,省略为auto,也可读AMAIL_PROVIDER_ID
发送只需收件人、主题和正文。发件邮箱由后台通道的「发件人覆盖」决定:
ts
const { data, error } = await amail.emails.send({
to: ['[email protected]'],
subject: '你好',
html: '<p>测试邮件</p>',
})
if (error) {
console.error(error.statusCode, error.name, error.message)
} else {
console.log(data.id)
}可选传入显示名。邮箱部分会被改成通道配置的地址:
ts
await amail.emails.send({
from: '客服', // 实际发出:客服 <[email protected]>
to: '[email protected]',
subject: '你好',
text: '测试邮件',
})API 错误返回 { data, error },不会抛异常。缺少 API Key 会在请求前抛异常。
emails.create() 与 emails.send() 相同。可用 idempotencyKey 去重:
ts
await amail.emails.send({
to: '[email protected]',
subject: '你好',
text: '测试邮件',
}, { idempotencyKey: 'order-123' })查询与列表
ts
const { data } = await amail.emails.get('email_id')
// data.last_event / data.status / data.from / data.html / data.text
const list = await amail.emails.list({ limit: 20 })
if (list.data?.has_more) {
const last = list.data.data.at(-1)
await amail.emails.list({ limit: 20, after: last.id })
}批量
ts
const { data, error } = await amail.batch.send([
{ to: '[email protected]', subject: '你好 1', text: '1' },
{ to: '[email protected]', subject: '你好 2', text: '2' },
], { batchValidation: 'permissive' })默认 strict:有一封不合法则整批失败。permissive 时 data.errors 为失败项。批量不支持附件,一次最多 100 封。
定时与改期
ts
await amail.emails.send({
to: '[email protected]',
subject: '稍后',
text: '定时',
scheduledAt: 'in 5 minutes',
})
await amail.emails.update('email_id', {
scheduledAt: new Date(Date.now() + 60000).toISOString(),
})
await amail.emails.cancel('email_id')
// 或 amail.emails.remove('email_id'),对应 DELETE /emails/:id仅 queued / scheduled 可取消;仅 scheduled 可改期。
指定 SMTP
默认 providerId 为 auto。需要钉死某条通道时再传:
ts
await amail.emails.send({
providerId: 'smtp_provider_id',
to: '[email protected]',
subject: '指定 SMTP',
text: '测试邮件',
})列出通道:
ts
const { data } = await amail.emails.providers()
// data.data: [{ id, name, host, from_address, from_name }]从 Resend 迁移
ts
import { Resend } from 'resend'
const resend = new Resend('re_xxx')
import { Amail } from '@wydev/amail'
const amail = new Amail('am_xxx', { baseUrl: 'https://mail.example.com' })方法名对齐:emails.send / create / get / list / update / cancel,以及 batch.send。不必传真实 From 邮箱。