此示例使用 Cloudflare Email Service 生成登录链接并通过电子邮件发送。
在 Wrangler 配置文件中配置邮件绑定:
{
"send_email": [{ "name": "EMAIL" }],
"vars": {
"DOMAIN": "yourdomain.com",
},
}[[send_email]]
name = "EMAIL"
[vars]
DOMAIN = "yourdomain.com"Worker 公开一个 POST /send-magic-link 路由。它会检查电子邮件地址、生成随机令牌,并通过电子邮件发送登录链接。
interface Env {
EMAIL: SendEmail;
DOMAIN: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/send-magic-link" && request.method === "POST") {
return handleSendMagicLink(request, env);
}
return new Response("Not Found", { status: 404 });
},
};
async function handleSendMagicLink(
request: Request,
env: Env,
): Promise<Response> {
const { email } = await request.json();
if (!email || !isValidEmail(email)) {
return new Response(JSON.stringify({ error: "Invalid email" }), {
status: 400,
});
}
// Generate a random token for the login link
const token = crypto.randomUUID();
const magicUrl = `https://${env.DOMAIN}/login?token=${token}`;
// Send magic link email
await env.EMAIL.send({
to: email,
from: `noreply@${env.DOMAIN}`,
subject: "Your login link",
html: `
<h1>Login to your account</h1>
<p>Click the link below to log in:</p>
<p><a href="${magicUrl}">Login Now</a></p>
`,
text: `
Login to your account
Click this link to log in: ${magicUrl}
`,
});
return new Response(
JSON.stringify({
success: true,
message: "Magic link sent to your email",
}),
);
}
function isValidEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}- User signup flow — 将魔术链接与账户验证结合使用。
- Send method —
send()方法的完整参考。 - Email headers — 添加跟踪或列表管理标头。