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:
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"| Key | Description |
|---|---|
binding | Name of the binding in your worker's env, uppercase with underscores. Required when from or allowed_from is set. |
from | Default sender, hello@acme.com or Acme <hello@acme.com>. Used when send() is called without from. |
allowed_from | Senders the worker may use: exact addresses or a whole domain as *@domain. Without it, any address on a verified domain of the organization works. |
receive | Addresses or whole domains (*@domain) whose email is delivered to the worker's email() handler. See Receiving email. |
inbox | true 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.
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-printableDeploy 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 suppliedAuthentication-Resultsnever 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 DKIMl=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:
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.
| Option | Type | Description |
|---|---|---|
to | string | string[] | Recipients. to, cc and bcc together hold at most 50 addresses. |
cc | string | string[] | Optional copy recipients. |
bcc | string | string[] | Optional blind copy recipients. |
from | string | Sender. Defaults to email.from. Must be on a verified domain and allowed by allowed_from. |
replyTo | string | Optional Reply-To address. |
subject | string | Subject line, required. |
text | string | Plain-text body. Pass text, html or both. |
html | string | HTML body. |
headers | object | Extra 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;
}| Code | Meaning |
|---|---|
invalid_request | The message is malformed, for example without a subject or body. |
invalid_sender | No sender was given and email.from is not set, or the address is invalid. |
sender_not_allowed | The sender is not covered by email.allowed_from. |
invalid_recipient | A recipient address is invalid. |
too_many_recipients | More than 50 recipients. |
access_not_approved | Email sending is not enabled for your organization. |
domain_not_verified | The sender's domain is not a verified domain of your organization. |
recipient_suppressed | A recipient bounced or marked earlier mail as spam. |
quota_exceeded | The project reached its daily limit. |
recipient_rate_limited | Too many emails to the same address within an hour. |
send_failed | The 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:
email:
binding: EMAIL
receive:
- "support@acme.ploy.email"
- "*@in.acme.com"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
| Property | Description |
|---|---|
from | The envelope sender. |
to | The address the email was received at. |
headers | The message headers as a Headers object. |
raw | The full message in MIME format, as a ReadableStream. |
rawSize | The 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 youremail()handler runs again. - Email your worker starts: send
froman address inemail.receive, or setreplyToto one. A deployment whoseemail.fromdoes 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:
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:
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.
email:
inbox: trueThe 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:
| Type | Name | Value | Priority |
|---|---|---|---|
| MX | <domain> | inbound-smtp.us-east-1.amazonaws.com | 10 |
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