Cloudflare Docs
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

EmailEvent

​​ Background

An EmailEvent is the event type to programmatically process your emails with a Worker. You can reject, forward, or drop emails according to the logic you construct in your Worker.


​​ Syntax: Service Worker

EmailEvent can be handled in Workers functions written using the Service Worker syntax by attaching to the email event with addEventListener:

addEventListener("email", (event) => {
event.message.forward("<YOUR_EMAIL>");
});

​​ Properties


​​ Syntax: Module Worker

EmailEvent can be handled in Workers functions written using the Module Worker syntax by adding an email function to your module’s exported handlers:

export default {
async email(message, env, ctx) {
message.forward("<YOUR_EMAIL>");
},
};

​​ Parameters

  • message EmailMessage

  • env object

    • An object containing the bindings associated with your Module Worker, such as KV namespaces and Durable Objects.
  • ctx object

    • An object containing the context associated with your Module Worker. Currently, this object just contains the waitUntil function.

​​ EmailMessage definition

interface EmailMessage<Body = unknown> {
readonly from: string;
readonly to: string;
readonly headers: Headers;
readonly raw: ReadableStream;
readonly rawSize: number;
setReject(reason: String): void;
forward(rcptTo: string, headers?: Headers): Promise<void>;
}
  • from string

    • Envelope From attribute of the email message.
  • to string

    • Envelope To attribute of the email message.
  • headers Headers

  • raw ReadableStream

    • Stream of the email message content.
  • rawSize number

    • Size of the email message content.
  • setReject(reasonstring) : void

    • Reject this email message by returning a permanent SMTP error back to the connecting client, including the given reason.
  • forward(rcptTostring, headersHeadersoptional) : Promise

    • Forward this email message to a verified destination address of the account. If you want, you can add extra headers to the email message. Only X-* headers are allowed.
    • When the promise resolves, the message is confirmed to be forwarded to a verified destination address.