跳转到内容

定时发送

在任何发送请求中加入 scheduled_at,即可延后投递。邮件会被立即接受,状态为 scheduled,并触发 email.scheduled Webhook。

格式 示例
ISO 8601 2026-11-01T09:00:00Z, 2026-11-01T09:00:00+01:00
自然语言 in 30 seconds, in 10 minutes, in 2 hours, in 1 day, in 1 week

自然语言的格式为 in <number> <unit>,其中 unit 可以是 second、sec、minute、min、hour、hr、day、week 之一(复数 s 可有可无)。文本不区分大小写。

其他规则:

  • 最多只能安排到未来 30 天。超出后 API 会返回 422 validation_error。
  • 过去的时间,或距现在不到约一秒的时间,会被视为立即发送。
  • 不带时区偏移的 ISO 字符串由服务器的日期解析器解释;请始终带上 Z 或时区偏移。
  • scheduled_at 和 scheduledAt 都可以使用。
schedule.ts
import { SpacePost } from "@spacepost/node";
const spacepost = new SpacePost(process.env.SPACEPOST_API_KEY);
const { data, error } = await spacepost.emails.send({
from: "Acme <hello@acme.com>",
to: "user@example.com",
subject: "Your trial ends tomorrow",
html: "<p>Reminder.</p>",
scheduledAt: "in 1 day", // or an ISO date: "2026-11-01T09:00:00Z"
});
if (error) console.error(error);
else console.log("Scheduled", data.id);

只有状态为 scheduled 的邮件才能修改。PATCH /emails/{id} 会替换发送时间;系统会加入一个新任务,旧任务则不再产生任何效果。

reschedule.ts
import { SpacePost } from "@spacepost/node";
const spacepost = new SpacePost(process.env.SPACEPOST_API_KEY);
const { error } = await spacepost.emails.update({
id: "0192e1c4-7a3b-7c1e-9d2f-3b5a8e6f4c10",
scheduledAt: "in 2 hours",
});
if (error) console.error(error);
Response (200)
{ "object": "email", "id": "0192e1c4-7a3b-7c1e-9d2f-3b5a8e6f4c10" }
cancel.ts
import { SpacePost } from "@spacepost/node";
const spacepost = new SpacePost(process.env.SPACEPOST_API_KEY);
const { error } = await spacepost.emails.cancel("0192e1c4-7a3b-7c1e-9d2f-3b5a8e6f4c10");
if (error) console.error(error); // 422 validation_error if it is no longer scheduled

状态会变为 canceled,邮件永远不会被发送。对已不再是 scheduled 状态的邮件执行取消或重新安排,会返回 422 validation_error(“Only scheduled emails can be canceled”)。

将 X-SpacePost-Scheduled-At 标头设置为 ISO 日期或自然语言的值。参见 SMTP 中继。