Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Workers API

最終更新 Markdown で表示Agent セットアップ

Workers API は、バインディングを通じて Cloudflare Workers からネイティブにメールを送信できます。Workers を使っていない場合は、代わりに REST API でメールを送信できます。

メールバインディング

Wrangler 構成ファイルに send_email バインディングを設定し、メール送信を有効にします。

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

バインディングが使える送信者と受信者は制限できます。利用可能な制限属性と例は 送信バインディングを設定する を参照してください。

send() メソッド

メールバインディングの send() メソッドで、1 通のメールを送信します。

インターフェイス

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、名前付きアドレスについては 受信者を指定する を参照してください。

添付ファイル

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",
		},
	],
});

インライン画像とファイルアップロードについては メールの添付ファイル を参照してください。

エラー処理

メール送信エラーを適切に処理します。

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 },
					);
			}
		}
	},
};

エラーコード

メール送信時に次のエラーコードが返されることがあります。

エラーコード 説明 よくある原因
E_VALIDATION_ERROR ペイロードの検証エラー 無効なメール形式、必須フィールドの欠落、不正なデータ
E_FIELD_MISSING 必須フィールドがない tofrom、または 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 ドロップがオフのときに抑制された受信者がいる 少なくとも 1 人の受信者が抑制されており、Drop suppressed recipients がオフ
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 ヘッダーが多すぎる 許可リスト上の(非 X)カスタムヘッダーが 20 を超えている

Drop suppressed recipients はデフォルトでオフです。設定をオン にすると、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: "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");
	},
};

次のステップ

  • Workers なしでメールを送信する場合は REST API を参照してください
  • SMTP 対応のアプリケーションまたはメールクライアントから送信する場合は SMTP を参照してください
  • メール送信パターンの 実践的な例 を参照してください
  • 受信メールの処理は メールルーティング を参照してください
  • 到達性を上げるには メール認証 を確認してください

役に立ちましたか?