Skip to content

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

メール

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

メールは、チャット UI ではなく受信トレイ経由でユーザーやシステムとやり取りするエージェント向けの通信チャネルです。エージェントはメールを送信し、受信し、返信を既存のセッションへ戻し、メール本文をエージェントのワークフローに組み込めます。

メールは、次のようなときに使います。

  • 通知、要約、領収書、フォローアップを送る。
  • Cloudflare Email Service 経由で受信メッセージを処理する。
  • 返信から会話を続ける。
  • サポート、営業、運用のワークフローをエージェント経由で振り分ける。

仕組み

送信メールは Worker の send_email バインディングを使います。受信メールは Email Service のルーティングルールで Worker に届き、エージェントが差出人、宛先、ヘッダー、本文を解析してから応答を決めます。

返信を扱うときは、返信アドレス、メッセージのメタデータ、またはヘッダーに安定した識別子を入れてください。Worker が後続メッセージを正しいエージェントインスタンスへルーティングできます。

基本的なパターン

受信メールは onEmail() で処理します。応答が必要なときは sendEmail() または replyToEmail() を使います。

import { Agent, callable, routeAgentEmail } from "agents";
import { createAddressBasedEmailResolver } from "agents/email";

export class EmailAgent extends Agent {
	@callable()
	async sendWelcomeEmail(to) {
		await this.sendEmail({
			binding: this.env.EMAIL,
			to,
			from: "support@yourdomain.com",
			replyTo: "support@yourdomain.com",
			subject: "Welcome",
			text: "Thanks for signing up. Reply to this email if you need help.",
		});
	}

	async onEmail(email) {
		await this.replyToEmail(email, {
			fromName: "Support Agent",
			body: "Thanks for your email. We received it.",
		});
	}
}

export default {
	async email(message, env) {
		await routeAgentEmail(message, env, {
			resolver: createAddressBasedEmailResolver("EmailAgent"),
		});
	},
};
import { Agent, callable, routeAgentEmail } from "agents";
import { createAddressBasedEmailResolver, type AgentEmail } from "agents/email";

export class EmailAgent extends Agent {
	@callable()
	async sendWelcomeEmail(to: string) {
		await this.sendEmail({
			binding: this.env.EMAIL,
			to,
			from: "support@yourdomain.com",
			replyTo: "support@yourdomain.com",
			subject: "Welcome",
			text: "Thanks for signing up. Reply to this email if you need help.",
		});
	}

	async onEmail(email: AgentEmail) {
		await this.replyToEmail(email, {
			fromName: "Support Agent",
			body: "Thanks for your email. We received it.",
		});
	}
}

export default {
	async email(message, env) {
		await routeAgentEmail(message, env, {
			resolver: createAddressBasedEmailResolver("EmailAgent"),
		});
	},
} satisfies ExportedHandler<Env>;

設定

送信メール用に send_email バインディングを追加し、受信メールを Worker へ送る Email Service のルーティングルールを設定します。

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "send_email": [
    {
      "name": "EMAIL",
      "remote": true
    }
  ]
}
[[send_email]]
name = "EMAIL"
remote = true

remote = true を指定すると、wrangler dev によるローカル開発中でも実際の Email Service API を呼び出せます。

メールエージェントを構築する

ドメイン設定、バインディング、受信ルーティング、安全な返信まで含む一連の手順は、メールエージェントの例を参照してください。

メールエージェント

Cloudflare Email Service と Agents SDK を使い、メールの送信、受信、ルーティング、返信を行うエージェントを構築します。

関連リソース

Email Service

Cloudflare Email Service でメールのルーティング、受信、送信を行います。

役に立ちましたか?