跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

电子邮件发送 Workers API

最后更新 查看 MarkdownAgent 设置

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

电子邮件绑定

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

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

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

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: "[email protected]",
    from: "[email protected]",
    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 编码的内容来发送文件。邮件总大小不得超过 25 MiB(包括附件)。

const response = await env.EMAIL.send({
    to: "[email protected]",
    from: "[email protected]",
    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: "[email protected]",
                from: "[email protected]",
                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 },
                    );
            }
        }
    },
};

错误代码

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

错误代码 描述 常见原因
E_VALIDATION_ERROR 有效负载验证错误 电子邮件格式无效、缺少必填字段、数据格式错误
E_FIELD_MISSING 缺少必填字段 缺少 to、from 或 subject 字段
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_ACCOUNT_SUSPENDED 账户的 Email Sending 已暂停 账户因发件信誉不佳而暂停
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)自定义标头

丢弃已抑制收件人 功能默认关闭。您启用该设置后,Email Service 会移除被抑制的收件人,并处理其余收件人。

旧版 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: "[email protected]" });
        msg.setRecipient("[email protected]");
        msg.setSubject("Legacy Email");
        msg.addMessage({
            contentType: "text/html",
            data: "<h1>Hello from legacy API</h1>",
        });

        const message = new EmailMessage(
            "[email protected]",
            "[email protected]",
            msg.asRaw(),
        );

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

后续步骤

这篇文档对您有帮助吗?