使用 wrangler dev 在本地测试邮件发送功能,以模拟邮件投递,并在部署前验证发送逻辑。
- 注册 Cloudflare 账户 ↗。
- 安装
Node.js↗。
Node.js 版本管理器
使用 Volta ↗ 或 nvm ↗ 等 Node 版本管理器,以避免权限问题并切换 Node.js 版本。本指南后续将介绍的 Wrangler 需要 Node 版本 16.17.0 或更高。
在 Wrangler 文件中配置 email 绑定:
{
"name": "email-sending-worker",
// Set this to today's date
"compatibility_date": "2026-08-17",
"send_email": [{ "name": "EMAIL" }],
}name = "email-sending-worker"
# Set this to today's date
compatibility_date = "2026-08-17"
[[send_email]]
name = "EMAIL"使用远程绑定是在本地开发 Email Service 的推荐方式。默认情况下,wrangler dev 会在本地模拟 email 绑定——邮件会记录到控制台,但不会真正发送。使用远程绑定时,Worker 在本地运行,但会通过 Email Service 发送真实邮件。
在 Wrangler 配置中为 email 绑定设置 remote: true:
{
"name": "email-sending-worker",
// Set this to today's date
"compatibility_date": "2026-08-17",
"send_email": [
{
"name": "EMAIL",
"remote": true,
},
],
}name = "email-sending-worker"
# Set this to today's date
compatibility_date = "2026-08-17"
[[send_email]]
name = "EMAIL"
remote = true然后照常运行 wrangler dev。对 env.EMAIL.send() 的调用会通过 Email Service 发送真实邮件,而 Worker 代码仍在本地运行。
在不使用远程绑定的情况下运行 wrangler dev 时,email 绑定会在本地模拟。邮件不会真正发送——邮件内容会记录到控制台,并保存到本地文件供检查。
export default {
async fetch(request, env, ctx) {
if (request.method !== "POST") {
return new Response("Method not allowed", { status: 405 });
}
try {
const emailData = await request.json();
console.log("Sending email:", {
to: emailData.to,
from: emailData.from,
subject: emailData.subject,
});
const response = await env.EMAIL.send(emailData);
return new Response(
JSON.stringify({
success: true,
id: response.messageId,
}),
{
headers: { "Content-Type": "application/json" },
},
);
} catch (error) {
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
},
};启动开发服务器:
npx wrangler dev发送测试邮件:
curl -X POST http://localhost:8787/ \
-H "Content-Type: application/json" \
-d '{
"to": "recipient@example.com",
"from": "sender@yourdomain.com",
"subject": "Test Email",
"html": "<h1>Hello from Wrangler!</h1>",
"text": "Hello from Wrangler!"
}'Wrangler 会显示类似如下输出:
[wrangler:info] send_email binding called with MessageBuilder:
From: sender@yourdomain.com
To: recipient@example.com
Subject: Test Email
Text: /tmp/miniflare-.../files/email-text/<message-id>.txt邮件内容(文本和 HTML)会保存到本地文件,部署前可检查这些文件以验证邮件结构。
本地开发会在本地模拟 send_email 绑定,但附件 content 中的 ArrayBuffer 值无法被本地模拟器序列化。如果传入 ArrayBuffer(例如图片或 PDF 附件),会看到类似如下错误:
Cannot serialize value: [object ArrayBuffer]解决方法: 本地开发期间对基于文本的附件使用字符串内容。要测试二进制附件(图片、PDF),请使用 npx wrangler deploy 部署 Worker,并对已部署版本进行测试。
此限制仅影响本地开发——在已部署的 Workers 上,ArrayBuffer 内容可正常工作。