Cloudflare
This transport is introduced in Upyo 0.7.0.
Cloudflare Email Service lets you send transactional email from domains you manage on Cloudflare. The @upyo/cloudflare package provides two transports for it:
CloudflareTransporttalks to its REST API with an API token, so it works from any runtime, including Node.js, Deno, Bun, and edge functions.CloudflareWorkerTransportsends through asend_emailbinding from code running on Cloudflare Workers, with no API token. See Cloudflare Workers below.
Both take the same messages and apply the same checks. The sections up to Cloudflare Workers describe the REST transport.
Installation
npm add @upyo/cloudflarepnpm add @upyo/cloudflareyarn add @upyo/cloudflaredeno add jsr:@upyo/cloudflarebun add @upyo/cloudflareGetting started
You need three things before sending:
- A domain on Cloudflare to send from. Once it is onboarded to Cloudflare Email Sending, messages can go to any recipient; before that, they can go only to the account's verified destination addresses.
- Your Cloudflare account ID.
- An API token with permission to send email.
import { createMessage } from "@upyo/core";
import { CloudflareTransport } from "@upyo/cloudflare";
const transport = new CloudflareTransport({
accountId: "your-account-id",
apiToken: "your-api-token",
});
const receipt = await transport.send(
createMessage({
from: "[email protected]",
to: "[email protected]",
subject: "Welcome!",
content: { text: "Thanks for signing up.", html: "<p>Thanks for signing up.</p>" },
}),
);
if (receipt.successful) {
console.log("Message sent with ID:", receipt.messageId);
} else {
console.error("Send failed:", receipt.errorMessages.join(", "));
}Keep the account ID and token in environment variables or a secret store rather than in source code.
Configuration
accountId- Your Cloudflare account ID.
apiToken- A Cloudflare API token with email sending permission.
baseUrl- API base URL. Defaults to
https://api.cloudflare.com/client/v4. timeout- Request timeout in milliseconds. Defaults to
30000. retries- How many times to retry a request that Cloudflare answered with
429or a5xxstatus. Defaults to3. The wait starts at 1 second and doubles, up to 10 seconds, or is as long as Cloudflare'sRetry-Afterheader asks. Sincetimeoutcovers each request but not these waits, pass anAbortSignaltosend()to bound the total time. Network failures and timeouts are not retried. Their receipts are stillretryable, which means another attempt may succeed, not that it is safe from duplicates; aRetryTransportwrapped around this transport retries them unless you exclude them. A retried5xxmay send a message twice; setretriesto0if that is worse for you than a failed send. headers- Additional HTTP headers to send with every request.
Supported features
- HTML and plain text content, CC, BCC, and a reply-to address, with display names on every address
- Attachments and inline images (referenced with
cid:URIs). An inline attachment without a content ID is sent as a regular attachment. - Custom headers, including
List-Unsubscribeand the reply threading fieldsinReplyToandreferences - Priority, sent as an
X-Priorityheader unless the message sets its own - Calendar invitations, attached as an invite.ics file
Some things are not available:
- Tags are ignored, since the API has no equivalent.
- Only the first reply-to address is used, since the API takes a single one.
- The
messageIdanddatefields of a message are ignored, because Cloudflare generates theMessage-IDandDateheaders itself (headers). - There is no batch endpoint, so
sendMany()sends messages one at a time.
Checks before sending
Both transports reject these messages before sending, with a validation receipt that is not retryable and whose error says what is wrong:
cloudflare.header_not_allowed- A custom header is one that Cloudflare generates, such as
Message-ID,Date, orDKIM-Signature(see Cloudflare's list). cloudflare.header_use_api_field- A custom header belongs in a message field:
From,To,Cc,Bcc,Subject, orReply-To. cloudflare.too_many_recipients- The message has more than 50 recipients across
to,cc, andbcc.
Cloudflare's other rules, such as its header allowlist and its size limits, are left to Cloudflare; a message that breaks one comes back as a failed receipt.
Delivery status
A successful receipt means Cloudflare accepted the message, and its messageId is the identifier Cloudflare returned. Cloudflare often queues a message instead of delivering it at once, so treat successful as “accepted for delivery”, not “delivered”.
A message that reaches at least one recipient is a success, even if Cloudflare reports that others bounced or are on the suppression list. A message that reaches none of them, because every recipient bounced or is on the suppression list, is a failure.
Error handling
A failed send returns a receipt with successful: false instead of throwing. Its errors carry the HTTP status code, a category, and whether retrying may help. Cancelling through the AbortSignal passed to send() throws as usual.
Each error has a code:
cloudflare.<number>- Cloudflare's own numeric error code, such as
cloudflare.10202. The errors from the response are inproviderDetails. If the response has no error code, the code iscloudflare.<HTTP status>. If Cloudflare answered with a2xxstatus but its reply cannot be read, the error is not retryable, because the message may have been sent; nor is a2xxreply that reports a failure.
cloudflare.header_not_allowed, cloudflare.header_use_api_field, cloudflare.too_many_recipients : The message failed a check before sending. Nothing was sent.
cloudflare.recipients_rejected- Cloudflare accepted the request, but every recipient bounced or is on the suppression list. Cloudflare's result, which lists them, is in
providerDetails. cloudflare.missing_message_id- Cloudflare accepted the request but did not return a message ID. The message may have been sent, so this failure is not retryable.
Cloudflare Workers
Code running on Cloudflare Workers can send through a send_email binding instead of the REST API. The binding belongs to the account the Worker runs in and carries the permission, so there is no account ID or API token to configure. Sending domains and verified destination addresses work as they do for the REST API. Declare the binding in wrangler.jsonc:
{
"send_email": [{ "name": "EMAIL" }]
}The binding can also be restricted to certain senders and recipients.
Then pass env.EMAIL to CloudflareWorkerTransport. The binding's type that wrangler types generates fits its binding option:
import { createMessage } from "@upyo/core";
import { CloudflareWorkerTransport } from "@upyo/cloudflare";
const transport = new CloudflareWorkerTransport({ binding: env.EMAIL });
const receipt = await transport.send(
createMessage({
from: "[email protected]",
to: "[email protected]",
subject: "Welcome!",
content: { text: "Thanks for signing up." },
}),
);Its options are:
binding- The
send_emailbinding, such asenv.EMAIL. retries- How many times to retry when the binding reports a rate limit (
E_RATE_LIMIT_EXCEEDED) or a server error (E_INTERNAL_SERVER_ERROR). Defaults to3. The wait starts at 1 second and doubles, up to 10 seconds. A retried server error may send a message twice; setretriesto0if that is worse for you than a failed send.
It behaves like the REST transport, including the checks before sending, with these differences:
- A failure's
codeis the binding's own, such ascloudflare.E_RATE_LIMIT_EXCEEDEDorcloudflare.E_VALIDATION_ERROR, and itsproviderDetailsis{ code, message }. - There is no
timeout:send()waits until the binding settles. Cancellation is best effort: the binding takes noAbortSignal, so aborting while it sends stopssend()from waiting, but the message may still go out. - Failures carry no
statusCodeorretryAfterMilliseconds. cloudflare.recipients_rejecteddoes not occur, because the binding reports a rejected recipient as an error such ascloudflare.E_RECIPIENT_SUPPRESSED.- Messages with attachments, including calendar invitations, fail in the local simulator of
wrangler dev; see Cloudflare's local development notes.