跳转到内容
搜索文档

Workers API

最后更新 查看 MarkdownAgent 设置

Workers API 通过绑定提供从 Cloudflare Workers 原生发送电子邮件的能力。若您未使用 Workers,可改用 REST API 发送邮件。

电子邮件绑定

在 Wrangler 配置文件中配置 send_email 绑定以启用邮件发送:

{
	"send_email": [{ "name": "EMAIL" }],
}
[[send_email]]
name = "EMAIL"

您可以限制绑定可使用的发件人与收件人。请参阅 Configure send bindings 了解可用的限制属性与示例。

send() 方法

通过电子邮件绑定上的 send() 方法发送单封邮件。

接口

interface SendEmail {
	send(message: EmailMessage | EmailMessageBuilder): Promise<EmailSendResult>;
}

interface EmailAddress {
	email: string;
	name?: string;
}

// Structured email builder (recommended)
interface EmailMessageBuilder {
	to: string | EmailAddress | (string | EmailAddress)[]; // Max 50 recipients
	from: string | EmailAddress;
	subject: string;
	html?: string;
	text?: string;
	cc?: string | EmailAddress | (string | EmailAddress)[];
	bcc?: string | EmailAddress | (string | EmailAddress)[];
	replyTo?: string | EmailAddress;
	attachments?: Attachment[];
	// Custom headers. See /email-service/reference/headers/
	headers?: { [key: string]: string };
	// The combined number of addresses in `to`, `cc`, and `bcc` must not
	// exceed 50. See /email-service/platform/limits/ for all limits.
}

interface Attachment {
	content: string | ArrayBuffer | ArrayBufferView; // Base64 string or binary content
	filename: string;
	type: string; // MIME type
	disposition: "attachment" | "inline";
	contentId?: string; // For inline attachments
}

interface EmailSendResult {
	messageId: string; // Unique email ID
}

// Errors are thrown as standard Error objects with a `code` property
// try { await env.EMAIL.send(...) } catch (e) { console.log(e.code, e.message) }

基本用法

const response = await env.EMAIL.send({
	to: "recipient@example.com",
	from: "welcome@yourdomain.com",
	subject: "Welcome to our service!",
	html: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
	text: "Welcome! Thanks for signing up.",
});

有关多个收件人、CC/BCC 与具名地址,请参阅 Specify recipients

附件

通过在 attachments 数组中包含 base64 编码的内容来发送文件。消息总大小(含附件)不得超过 5 MiB。

const response = await env.EMAIL.send({
	to: "customer@example.com",
	from: "invoices@yourdomain.com",
	subject: "Your Invoice",
	html: "<h1>Invoice attached</h1><p>Please find your invoice attached.</p>",
	attachments: [
		{
			content: "JVBERi0xLjQKJeLjz9MKMSAwIG9iag...", // Base64 PDF content
			filename: "invoice-12345.pdf",
			type: "application/pdf",
			disposition: "attachment",
		},
	],
});

有关内联图片与文件上传,请参阅 Email attachments

错误处理

妥善处理邮件发送错误:

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		try {
			const response = await env.EMAIL.send({
				to: "user@example.com",
				from: "noreply@yourdomain.com",
				subject: "Test Email",
				text: "This is a test email.",
			});

			return new Response(
				JSON.stringify({
					success: true,
					emailId: response.messageId,
				}),
			);
		} catch (error) {
			// Error has .code and .message properties
			console.error("Email sending failed:", error.code, error.message);

			// Handle specific error types
			switch (error.code) {
				case "E_SENDER_NOT_VERIFIED":
					return new Response(
						JSON.stringify({
							success: false,
							error: "Please verify your sender domain first",
						}),
						{ status: 400 },
					);

				case "E_RATE_LIMIT_EXCEEDED":
					return new Response(
						JSON.stringify({
							success: false,
							error: "Rate limit exceeded. Please try again later",
						}),
						{ status: 429 },
					);

				default:
					return new Response(
						JSON.stringify({
							success: false,
							error: error.message,
						}),
						{ status: 500 },
					);
			}
		}
	},
};

错误代码

发送邮件时可能返回以下错误代码:

Error Code Description Common Causes
E_VALIDATION_ERROR 有效负载验证错误 电子邮件格式无效、缺少必填字段、数据格式错误
E_FIELD_MISSING 缺少必填字段 缺少 tofromsubject 字段
E_TOO_MANY_RECIPIENTS to/cc/bcc 数组中收件人过多 收件人合计超过 50 的限制
E_TOO_MANY_ATTACHMENTS attachments 数组中附件过多 attachments 数组超过 32 项
E_SENDER_NOT_VERIFIED 发件人域名未验证 尝试从未验证的域名发送
E_RECIPIENT_NOT_ALLOWED 收件人不在允许列表中 收件人地址不在 allowed_destination_addresses
E_RECIPIENT_SUPPRESSED 收件人在抑制列表中 该电子邮件地址曾退信或将您的邮件报告为垃圾邮件
E_SENDER_DOMAIN_NOT_AVAILABLE 域名不可用于发送 域名未接入 Email Service
E_CONTENT_TOO_LARGE 邮件内容超出大小限制 消息总大小超过最大值
E_DELIVERY_FAILED 无法投递邮件 SMTP 投递失败、收件服务器拒绝
E_RATE_LIMIT_EXCEEDED 超出速率限制 已达到发送速率限制
E_DAILY_LIMIT_EXCEEDED 超出每日限制 已达到每日发送配额
E_INTERNAL_SERVER_ERROR 内部服务错误 Email Service 暂时不可用
E_HEADER_NOT_ALLOWED 不允许使用该标头 标头由平台控制,或不在允许列表
E_HEADER_USE_API_FIELD 必须使用 API 字段 From 等标头必须通过专用 API 字段设置
E_HEADER_VALUE_INVALID 标头值无效 值格式错误、为空或格式不正确
E_HEADER_VALUE_TOO_LONG 标头值过长 值超过 2,048 字节限制
E_HEADER_NAME_INVALID 标头名称无效 包含无效字符或超过 100 字节限制
E_HEADERS_TOO_LARGE 标头有效负载过大 自定义标头总计超过 16 KB 限制
E_HEADERS_TOO_MANY 标头过多 超过 20 个在允许列表中的(非 X)自定义标头

旧版 EmailMessage API

为保持向后兼容,仍支持 EmailMessage API。当您已有要发送的原始 RFC 5322 MIME 消息时使用它。对于新代码,建议使用上方结构化的 send() 方法

import { EmailMessage } from "cloudflare:email";
import { createMimeMessage } from "mimetext";

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const msg = createMimeMessage();
		msg.setSender({ name: "Sender", addr: "sender@yourdomain.com" });
		msg.setRecipient("recipient@example.com");
		msg.setSubject("Legacy Email");
		msg.addMessage({
			contentType: "text/html",
			data: "<h1>Hello from legacy API</h1>",
		});

		const message = new EmailMessage(
			"sender@yourdomain.com",
			"recipient@example.com",
			msg.asRaw(),
		);

		await env.EMAIL.send(message);
		return new Response("Legacy email sent");
	},
};

后续步骤

  • 参阅 REST API,了解如何在不使用 Workers 的情况下发送邮件
  • 参阅 SMTP,了解如何从任何支持 SMTP 的应用或邮件客户端发送
  • 参阅邮件发送模式的实用示例
  • 了解用于处理传入邮件的 email routing
  • 探索 email authentication 以提升投递率

这篇文档对您有帮助吗?