|
| 1 | +--- |
| 2 | +title: Threaded replies now possible in Email Workers |
| 3 | +description: You can now use Email Workers to send multiple replies to the same email thread. |
| 4 | +date: 2025-03-12T18:00:00Z |
| 5 | +--- |
| 6 | + |
| 7 | +We’re removing some of the restrictions in Email Routing so that AI Agents and task automation can better handle email workflows, including how Workers can [reply](/email-routing/email-workers/reply-email-workers/) to incoming emails. |
| 8 | + |
| 9 | +It's now possible to keep a threaded email conversation with an [Email Worker](/email-routing/email-workers/) script as long as: |
| 10 | + |
| 11 | +* The incoming email has to have valid [DMARC](https://www.cloudflare.com/learning/dns/dns-records/dns-dmarc-record/). |
| 12 | +* The email can only be replied to once in the same `EmailMessage` event. |
| 13 | +* The recipient in the reply must match the incoming sender. |
| 14 | +* The outgoing sender domain must match the same domain that received the email. |
| 15 | +* Every time an email passes through Email Routing or another MTA, an entry is added to the `References` list. We stop accepting replies to emails with more than 100 `References` entries to prevent abuse or accidental loops. |
| 16 | + |
| 17 | +Here's an example of a Worker responding to Emails using a Workers AI model: |
| 18 | + |
| 19 | +```ts title="AI model responding to emails" |
| 20 | +import PostalMime from "postal-mime"; |
| 21 | +import {createMimeMessage} from "mimetext" |
| 22 | +import { EmailMessage } from "cloudflare:email"; |
| 23 | + |
| 24 | +export default { |
| 25 | + async email(message, env, ctx) { |
| 26 | + const email = await PostalMime.parse(message.raw) |
| 27 | + const res = await env.AI.run('@cf/meta/llama-2-7b-chat-fp16', { |
| 28 | + messages: [{ |
| 29 | + role: "user", |
| 30 | + content: email.text ?? '' |
| 31 | + }] |
| 32 | + }) |
| 33 | + |
| 34 | + // message-id is generated by mimetext |
| 35 | + const response = createMimeMessage() |
| 36 | + response.setHeader("In-Reply-To", message.headers.get("Message-ID")!); |
| 37 | + response. setSender( "[email protected]"); |
| 38 | + response.setRecipient(message.from); |
| 39 | + response.setSubject("Llama response"); |
| 40 | + response.addMessage({ |
| 41 | + contentType: 'text/plain', |
| 42 | + data: res instanceof ReadableStream ? await new Response(res).text() : res.response! |
| 43 | + }) |
| 44 | + |
| 45 | + const replyMessage = new EmailMessage("<email>", message.from, response.asRaw()); |
| 46 | + await message.reply(replyMessage) |
| 47 | + } |
| 48 | +} satisfies ExportedHandler<Env>; |
| 49 | +``` |
| 50 | + |
| 51 | +See [Reply to emails from Workers](/email-routing/email-workers/reply-email-workers/) for more information. |
0 commit comments