Ploy
Ploy
Email

Email in workers

Send email from your worker code and receive email in an email() handler.

Email in workers

Workers can send email through Ploy Email with a binding, and receive email sent to your domains in an email() handler. Ploy sends from your organization's verified domains and applies the same approval, suppression and limits as every other email your organization sends.

Sending requires email access for your organization and a verified sending domain: your <name>.ploy.email domain or a custom domain.

Configuration

Add an email section to your ploy.yaml:

ploy.yaml
kind: worker
build: pnpm build
out: dist
email:
  binding: EMAIL
  from: "Acme <hello@acme.ploy.email>"
  allowed_from:
    - "*@acme.ploy.email"
    - "support@mail.acme.com"
KeyDescription
bindingName of the binding in your worker's env, uppercase with underscores. Required when from or allowed_from is set.
fromDefault sender, hello@acme.com or Acme <hello@acme.com>. Used when send() is called without from.
allowed_fromSenders the worker may use: exact addresses or a whole domain as *@domain. Without it, any address on a verified domain of the organization works.
receiveAddresses or whole domains (*@domain) whose email is delivered to the worker's email() handler. See Receiving email.
inboxtrue gives the project a private, receive-only inbox address. Works without email access. See Inbox address.

The settings are taken from your production deployment's ploy.yaml. Preview deployments use the same settings as production.

Run ploy types to add EMAIL: EmailBinding to your worker's Env type.

Start a message from your own inbox

email.compose is a separate, explicit opt-in. It lets an authorized mailbox start a fresh customer message from your support identity, without putting the private mailbox in the outgoing transport headers. It does not enable a public relay and does not change relayReplies.

ploy.yaml
email:
  binding: EMAIL
  from: "Acme Support <support@acme.com>"
  allowed_from:
    - "support@acme.com"
  receive:
    - "support@acme.com"
  compose:
    receive: "compose@acme.com"
    from: "Acme Support <support@acme.com>"
    senders:
      - "owner@example.com"
    # Explicit fixed decoder for providers that leave MIME headers unsigned:
    format: plain-utf8-quoted-printable

Deploy this configuration to turn it on. Remove compose and deploy to turn it off. The compose address is reserved by Ploy and is never delivered to the worker when enabled. Both addresses must belong to verified receiving domains on this project. The sending address must also be an exact receive entry, so customer replies continue into the normal support handler. Keep forwarding that address with { relayReplies: true } to answer privately from your inbox.

Compose a new message, not a reply or forward, in your normal mail app:

From: owner@example.com
To: compose@acme.com
Subject: [to:customer@example.net] Your account question

Ploy-Compose: plain-utf8-quoted-printable

Hello! Here is the information you requested.

With the fixed profile shown above, select plain text in your mail app, without attachments. The exact Ploy-Compose: plain-utf8-quoted-printable line must be the first body line, followed by one blank line. It is part of the signed payload and positively binds your intent to the fixed decoder; Ploy removes it from the customer message. Your app must send UTF-8 quoted-printable text. HTML, multipart, attachments, contradictory MIME and invalid encoded text are refused. Ploy never uses unsigned headers to choose a decoder.

Omit format for the default signed-MIME profile, which can preserve HTML and attachments but requires every copied MIME header to be covered by valid DKIM; it does not use the plain-text prelude. Providers such as Proton commonly leave MIME headers unsigned, so use the explicit fixed profile instead of weakening sender authentication.

Use exactly one bare destination in the subject instruction; no display names, Cc, Bcc, commas or multiple recipients. The actual To header must contain only the compose mailbox, without a +tag or a list/group. A normal, unambiguous display name added by your mail app is accepted. The subject after the instruction is 1–500 printable ASCII characters; Unicode is supported in the body, not the subject instruction. The customer sees Your account question, not the instruction, and receives a new message from Acme Support <support@acme.com>.

Sender authentication and safety

  • Only 1–10 explicitly listed, exact sender mailboxes can compose. Wildcards and automatic authorization of a forwarding destination are not supported.
  • Ploy cryptographically verifies DKIM on the stored raw message. Its signing domain must exactly match the allowed mailbox domain (strict DMARC DKIM alignment). A forged From, SPF alone, or supplied Authentication-Results never authorizes a send. RSA keys must be at least 2048 bits; SHA-1 is refused.
  • The valid signature must cover From, To, Subject, Date, Message-ID, every copied MIME header, and the entire body, without DKIM l= truncation. The default profile requires the sender mail service to sign MIME headers. The fixed plain profile copies none: its interpretation comes from trusted config and the authenticated body prelude, never unsigned input metadata.
  • Messages must be under 1 MiB, less than one hour old (five minutes of forward clock skew is allowed), and manually composed. Replies, list mail, automated reports, copies, duplicate semantic headers and malformed instructions are refused. Owner, support, compose, private relay and bounce-handler destinations are not permitted. Normal organization sending approval, suppression and recipient limits still apply, plus a separate 25-message/project/UTC-day cap.
  • Each authenticated sender/Message-ID pair has a durable dispatch claim. Retries and duplicate deliveries cannot send it again or consume extra quota. An uncertain send is never automatically retried; inspect the project email history before composing a new message with a new Message-ID. Rejections are visible in email history; no automatic rejection email is sent.

Ploy rebuilds the outgoing envelope and headers: public From and Reply-To, one customer recipient, a new Date and Message-ID, the clean subject, and necessary MIME headers only. Private routing, original identity, DKIM, Received, Sender, Reply-To, threading, authentication and X-headers are not carried across. The body and attachments are user-provided content, including signatures, quoted text, names, tracking links and attached-message metadata. Review them before sending; transport privacy does not redact that content. Delivery requires recipient-side confirmation, not merely API/SES acceptance.

Sending email

Call send() on the binding:

src/index.ts
export default {
	async fetch(request: Request, env: Env) {
		const { id } = await env.EMAIL.send({
			to: "jane@example.com",
			subject: "Your order has shipped",
			text: "Your order #1234 is on its way.",
			html: "<p>Your order <strong>#1234</strong> is on its way.</p>",
		});
		return Response.json({ id });
	},
};

send() resolves once Ploy has accepted the email for delivery, with its Ploy id and its messageId, the Message-ID header recipients see. A reply to the email carries that messageId in its In-Reply-To header; see Conversations.

OptionTypeDescription
tostring | string[]Recipients. to, cc and bcc together hold at most 50 addresses.
ccstring | string[]Optional copy recipients.
bccstring | string[]Optional blind copy recipients.
fromstringSender. Defaults to email.from. Must be on a verified domain and allowed by allowed_from.
replyTostringOptional Reply-To address.
subjectstringSubject line, required.
textstringPlain-text body. Pass text, html or both.
htmlstringHTML body.
headersobjectExtra headers: In-Reply-To, References, List-Id, List-Unsubscribe, List-Unsubscribe-Post and custom X-* headers.

An email goes out to all of its recipients or to none: if any recipient is refused, for example because it is on the suppression list, nothing is sent. Every recipient counts towards your project's daily limit.

Errors

When Ploy refuses an email, send() throws an error with a code:

try {
	await env.EMAIL.send({ to, subject, text });
} catch (error) {
	if (error instanceof Error && "code" in error) {
		console.warn("Email refused:", error.code, error.message);
	}
	throw error;
}
CodeMeaning
invalid_requestThe message is malformed, for example without a subject or body.
invalid_senderNo sender was given and email.from is not set, or the address is invalid.
sender_not_allowedThe sender is not covered by email.allowed_from.
invalid_recipientA recipient address is invalid.
too_many_recipientsMore than 50 recipients.
access_not_approvedEmail sending is not enabled for your organization.
domain_not_verifiedThe sender's domain is not a verified domain of your organization.
recipient_suppressedA recipient bounced or marked earlier mail as spam.
quota_exceededThe project reached its daily limit.
recipient_rate_limitedToo many emails to the same address within an hour.
send_failedThe email could not be sent. Retrying later may work.

Receiving email

List the addresses your worker receives email at under email.receive, and export an email() handler:

ploy.yaml
email:
  binding: EMAIL
  receive:
    - "support@acme.ploy.email"
    - "*@in.acme.com"
src/index.ts
export default {
	async email(message, env, ctx) {
		const subject = message.headers.get("subject") ?? "";
		if (subject.toLowerCase().includes("unsubscribe")) {
			message.setReject("Unsubscribe requests are handled elsewhere");
			return;
		}
		await message.forward("team@acme.com");
		await message.reply({
			text: "Thanks for your message, we'll get back to you soon.",
		});
	},
} satisfies Ploy;

A pattern is either an exact address or a whole domain as *@domain. When both match, the exact address wins. An exact address also receives its +tag variants: support@acme.ploy.email receives support+order-42@acme.ploy.email too. Each address can belong to only one project of your organization; a deployment that claims an address another project already receives at fails with an error in the build logs. Like the other email settings, receive is taken from your production deployment.

Email arrives at the project's production deployment. The binding key is only needed if the worker also calls send().

The message

PropertyDescription
fromThe envelope sender.
toThe address the email was received at.
headersThe message headers as a Headers object.
rawThe full message in MIME format, as a ReadableStream.
rawSizeThe size of the raw message in bytes.
setReject(reason)Marks the email as rejected. It shows as rejected in the dashboard; the sender is not notified.
forward(to, headers?, options?)Forwards the email. It is sent from the address it was received at, with the sender as Reply-To.
reply({ subject?, text?, html? })Replies to the sender from the address the email was received at, in the same thread.

forward() and reply() send email, so they need email access and count towards your daily limit like send(). Messages up to 25 MB are delivered; up to 10 MB can be forwarded.

Conversations

A customer's reply goes to the address your worker sent from (or its replyTo), so keep that address in email.receive:

  • Replies to received email: reply() sends from the address the email arrived at, threaded on the original. When the customer answers, the email arrives at the same address and your email() handler runs again.
  • Email your worker starts: send from an address in email.receive, or set replyTo to one. A deployment whose email.from does not receive email logs a warning, since replies to it would be dropped.

To tell conversations apart, put an ID in a +tag. Sending from support+order-42@acme.ploy.email works whenever support@acme.ploy.email is allowed, and the customer's reply arrives with message.to set to the tagged address:

src/index.ts
export default {
	async fetch(request: Request, env: Env) {
		const { messageId } = await env.EMAIL.send({
			from: "Acme Support <support+order-42@acme.ploy.email>",
			to: "jane@example.com",
			subject: "About your order #42",
			text: "Your order is delayed by a day.",
		});
		// Store messageId to match the reply's In-Reply-To header too.
		return Response.json({ messageId });
	},
	async email(message, env) {
		const tag = /\+([^@]+)@/.exec(message.to)?.[1]; // "order-42"
		const inReplyTo = message.headers.get("in-reply-to");
		// Look up the conversation by tag or inReplyTo, then answer:
		await message.reply({ text: "Thanks, we're on it." });
	},
} satisfies Ploy<Env>;

send() and reply() both return the email's messageId; to continue a thread with send(), pass the last one as In-Reply-To and References in headers.

Reply from your own inbox

A plain forward() sets the original sender as Reply-To, so answering the forward from your mail app sends the reply from your own address. To answer as the address the email arrived at instead, forward with relayReplies:

src/index.ts
export default {
	async email(message) {
		await message.forward("me@example.com", undefined, { relayReplies: true });
	},
} satisfies Ploy;

The forward's From and Reply-To are then a private address next to the receiving one, like support+ploy-3f9a0c27d1b84e6f5a20@acme.com. When me@example.com replies to it, Ploy sends the reply to the original sender from support@acme.com, in the same thread. Your address is not shown to the original sender, but anything in the body of your reply is, such as your signature.

  • Only the forward target can reply. The reply must come from the address you forwarded to, and its domain must pass DMARC, or SPF for the From domain itself. Other email to the address is dropped.
  • Nothing else follows the forward. The forward is addressed to the forward target only and drops the original Cc. Both From and Reply-To use the private address, so Reply All does not copy the original receiving address back into your worker. Relayed replies go to the original sender alone.
  • Automatic replies are not relayed, such as out-of-office messages and bulk mail.
  • The address expires 30 days after it was created or last relayed a reply.

Relayed replies never reach your email() handler. They show as Relayed on the Email page and count towards your daily limit like send(). The receiving address needs a domain that can send, so relayReplies does not work for an inbox address. Removing the receiving route, transferring the project to another organization or disabling the domain stops existing relays too.

Addresses matching <name>+ploy-<20 hexadecimal characters>@<domain> are reserved for relays, even under a wildcard route. The receiving address must not start with +, and its untagged local part must leave room for the 26-character relay tag within the 64-character local-part limit.

Delivery

Valid, routed email is delivered to the worker at least once. When the handler throws or the deployment cannot be reached, Ploy tries again after 30 seconds, 2 minutes and 10 minutes before marking the email as failed. Email classified as spam or containing a virus, and email to addresses no project receives at, is not delivered. The Email page in the dashboard lists received emails from the last 30 days with their status.

Delivery failures

With the SES provider, Ploy queues a standard delivery-failure report when an address has no receiving route (5.1.1), or delivery fails permanently after retries (5.3.0). The report goes to the original SMTP envelope sender, not the message's From or Reply-To address. It does not expose worker errors or configuration values.

Ploy also alerts verified organization owners and admins on the first worker delivery failure, limited to one alert per project per hour. A later permanent bounce of a forwarded message marks the original delivery failed and can notify its sender too: the worker completing successfully does not mean the forward reached its destination.

To prevent mail loops and forged-sender backscatter, failure reports require successful SPF and DMARC checks, clean spam/virus verdicts and complete, non-automated headers. Ploy never sends reports for spam, viruses, automated messages, explicit setReject() decisions, or unknown/unverified domains. Reports are rate-limited, subject to suppression rules, and expire after 24 hours. Ambiguous provider outcomes are not retried, preventing duplicate reports. SMTP-only providers do not generate these native reports.

Inbox address

For automations that only need to receive email, such as parsing invoices or feeding an agent, set inbox: true. Ploy gives the project a private address like 3f9a0c27d1b84e6f5a20@in.ploy.email and delivers its email to the email() handler. No email access or domain is needed.

ploy.yaml
email:
  inbox: true

The address is listed in the build logs and on the Email page, and stays the same across deployments. It is random, so only senders you give it to can reach it. Removing inbox (or the whole email section) releases the address; turning it on again creates a new one.

An inbox address only receives: forward() and reply() fail with invalid_sender. Each organization's inboxes receive up to 1,000 emails per day; further email is dropped.

Your own domain

Your <name>.ploy.email domain receives email without any setup. To receive at a custom domain, first enable your organization's email access, then add and verify the domain on the Email page and turn on Receive email. Once email access is enabled, new domains do not need individual approval: verification and DNS setup are handled through the dashboard.

Receiving adds an MX record to the domain's records:

TypeNameValuePriority
MX<domain>inbound-smtp.us-east-1.amazonaws.com10

On Ploy DNS the record is added for you. The MX record sends all of the domain's email to Ploy, so use a subdomain such as in.acme.com rather than a domain whose mailboxes you already use.

Only verified domains with receiving enabled deliver email. Turning receiving off, removing a route, or suspending email access also stops queued deliveries that have not reached the worker yet.

Local development

Under ploy dev, nothing is sent. send() checks the message against your ploy.yaml like in production, and every email lands in the local inbox: open the dev dashboard and go to Email to read it.

To test your email() handler, use Send test email on the same page. The email is delivered to your local worker; its replies and forwards land in the local inbox. To test relayReplies, send a test email from the forward target to the Reply-To address shown on the forward: the relayed reply lands in the local inbox too.

How is this guide?

Last updated on