
Summary
Key points of this document
- Introduction: The Need for Coexistence of Business Emails and Edge System Sending
- Why it's Tricky: Structural Dependencies Between Cloudflare Email Routing and SendEmail
- Architectural Decision: Subdomain Separation vs. Coexistence on the Same Domain
Introduction: The Need for Coexistence of Business Emails and Edge System Sending
When designing and operating web services and business systems, selecting an email delivery infrastructure is always a critical consideration.
It is not uncommon for corporate domains to have long-standing, stable operations for business emails (sending/receiving quotes, communicating with clients, internal correspondence, etc.) used daily by employees, leveraging the reliable and cost-effective email server functions (IMAP/POP3/SMTP) of rental servers (such as XSERVER).
Meanwhile, there are increasing opportunities to build web applications, APIs, and batch processes using Cloudflare Workers, a modern edge computing environment. This naturally creates requirements to send emails instantly and with low latency from an edge serverless environment, such as automatic replies to form inquiries, one-time password (OTP) transmissions, and completion notifications for periodic batches.
Traditionally, it was common to individually contract and implement external transactional email services like SendGrid, Amazon SES, or Resend for such system email sending. However, Cloudflare Workers offers a native SendEmail binding (send_email), which allows direct email sending as an internal Worker binding, reducing the need for external SaaS API key management and additional costs.
The problem here is "how to design a system to safely coexist Cloudflare Workers' system sending from the same domain or a dedicated subdomain, without interrupting existing business email operations on XSERVER."
Careless configuration can lead to a serious communication failure, where all incoming emails to the company's main email address or employees fail to be delivered. This article systematically explains the nature of the technical pitfalls in this configuration, the coexistence design of DNS records (MX, SPF, DKIM, DMARC), implementation using Wrangler, and verification procedures.
Why it's Tricky: Structural Dependencies Between Cloudflare Email Routing and SendEmail
The most common pitfall for engineers in this configuration lies in the prerequisite relationship between Cloudflare's Email Routing and the Workers SendEmail binding.
SendEmail Binding Depends on Email Routing Infrastructure
The SendEmail binding in Cloudflare Workers is not a standalone, general-purpose SMTP client. It delivers emails by utilizing the outbound infrastructure of the "Email Routing" feature within the Cloudflare infrastructure.
Therefore, to send emails from Workers, Email Routing must be enabled for the target domain.
The Biggest Pitfall: Total Loss of Incoming Emails Due to Applying "Recommended MX Records"
When you try to enable Email Routing on the Cloudflare dashboard, the wizard screen displays the following message:
"To receive and forward emails, please add Cloudflare's MX records (
route1.mx.cloudflare.netetc.) to your DNS."
If you inadvertently click buttons like "Add Recommended Settings in Bulk" here, the MX records for your root domain will be overwritten from XSERVER to Cloudflare.
【Incorrect Configuration Flow】
1. Existing DNS settings:
example.com. IN MX 10 example.com.v4.xserver.jp. (Receiving with XSERVER)
↓
2. MX updated according to Cloudflare dashboard instructions:
example.com. IN MX 13 route1.mx.cloudflare.net.
example.com. IN MX 54 route2.mx.cloudflare.net.
example.com. IN MX 89 route3.mx.cloudflare.net.
↓
3. Result:
All emails sent from external sources to employee or representative addresses are routed to Cloudflare,
and not a single email reaches XSERVER (complete loss of general business emails).Boundary of Responsibility for Sending (Outbound) and Receiving (Inbound)
The essence of this problem stems from confusing the DNS responsibilities of "email sending" and "email receiving."
- MX Record: A record that specifies the mail server that receives emails sent to that domain (Inbound).
- SPF / DKIM Record: A record that declares the servers and public keys authorized to send emails from that domain (Outbound).
In fact, if you only need to send emails externally from a Cloudflare Workers SendEmail binding, it is technically not necessary for the MX record to point to Cloudflare. Even if the MX record continues to point to XSERVER, as long as appropriate SPF and DKIM settings exist, emails sent from Workers will successfully pass recipient spam filters.
On the Cloudflare dashboard, a warning status will continue to be displayed, stating "Email Routing is incomplete because MX records are not set," but the sending function itself will operate without issues. Understanding this boundary of specification is the first step.
Architectural Decision: Subdomain Separation vs. Coexistence on the Same Domain
There are two main design patterns for coexisting with an existing XSERVER environment.
Pattern A: Subdomain Separation (Recommended)
[Business Email (Receive/Send)] ──> example.com (XSERVER / MX, SPF, DKIM independent)
[System Email (Send)] ──> sys.example.com (Cloudflare Workers / SendEmail)
Pattern B: Coexistence on the Same Domain
[Business Email (Receive/Send)] ──> example.com (XSERVER / MX maintained)
[System Email (Send)] ──> example.com (Cloudflare Workers / SPF merged, DKIM selector separated)Pattern A: Subdomain Separation (Recommended Approach)
This method involves creating a dedicated subdomain for system-generated emails (e.g., sys.example.com or mail.example.com).
- Benefits:
- Since there is no need to modify the MX or SPF records of the root domain (
example.com), the risk of incidents affecting existing business emails becomes completely zero. - If you use a subdomain, setting up Cloudflare Email Routing's MX records will not affect XSERVER's email reception at all.
- Future bounce handling and forwarding rules can be freely configured on the Email Routing side.
- Since there is no need to modify the MX or SPF records of the root domain (
- Disadvantages:
- The sender address will look like
noreply@sys.example.com, which is different from the address of the root domain alone (noreply@example.com).
- The sender address will look like
Pattern B: Coexistence on the same domain (if required)
This method is adopted when there are brand requirements or recipient recognition considerations that necessitate unifying the sender address to noreply@example.com.
- Advantages:
- The domain of the sender email address will be the corporate domain itself.
- Disadvantages:
- The root domain's SPF record must be carefully merged to include both the Xserver and Cloudflare settings.
- Since the MX record will remain pointed to Xserver, it is necessary to correctly understand and manage the warnings in the Cloudflare dashboard.
In practice, Pattern A (subdomain separation) is primarily recommended whenever requirements allow. Pattern B (same-domain coexistence) is meticulously designed and applied only when sending from the same domain is essential. The following section explains DNS design, focusing on Pattern B (same-domain coexistence), which involves more technical considerations.
Specific DNS Design (SPF / DKIM / DMARC)
This section shows the specific DNS record design for coexisting Xserver and Cloudflare Workers on the same domain.
1. Protecting MX Records (Strictly Maintaining Xserver's Specification)
The MX record for the root domain must always maintain the values specified by Xserver. Cloudflare's MX records (route*.mx.cloudflare.net) must never be added or replaced.
| Record Type | Hostname (Name) | Value / Target | Priority | Notes |
|---|---|---|---|---|
| MX | @(example.com) | example.com.v4.xserver.jp. | 10 | XSERVER incoming server (maintain existing) |
※ Set the server number and hostname of XSERVER to the values confirmed in the XSERVER server panel "Server Information" or "DNS Record Settings".
2. Combining SPF Records
SPF (Sender Policy Framework) is a mechanism to verify whether the sender's IP address and domain are legitimate senders.
Critical Rule: According to RFC 7208, only one SPF record (TXT record) can be published for a single domain. If you register two TXT records, one for XSERVER and one for Cloudflare, it will result in PermError (permanent error), and all emails will be undeliverable or marked as spam by receiving servers like Gmail.
Example of existing XSERVER SPF:
v=spf1 +a:svXXX.xserver.jp include:spf.xserver.jp ~allCloudflare Email Routing SPF specification:
include:_spf.mx.cloudflare.netCombined SPF record:
`textv=spf1 +a:svXXX.xserver.jp include:spf.xserver.jp include:_spf.mx.cloudflare.net ~all
`
| Record Type | Hostname | Value | Notes |
|---|---|---|---|
| TXT | @ | v=spf1 +a:svXXX.xserver.jp include:spf.xserver.jp include:_spf.mx.cloudflare.net ~all | Integrated into a single record |
[!NOTE]
Caution regarding DNS lookup count (10-lookup limit)
The maximum number of DNS lookups during SPF evaluation is set to 10.
include:spf.xserver.jpandinclude:_spf.mx.cloudflare.nettypically combine to only about 3-4 lookups, so there's no issue. However, if you add more external services (such as MA tools or CRMs), be careful not to exceed 10 lookups.
3. DKIM Record Selector Separation
DKIM (DomainKeys Identified Mail) is a technology that adds an electronic signature to outgoing emails to detect tampering and prove the sender's identity.
DKIM registers public keys in DNS using a prefix called a "selector." If the selector names are different, multiple DKIM public key records can coexist under the same domain without conflict.
DKIM for XSERVER:
When you enable the XSERVER server panel's "DKIM settings",
default._domainkeya TXT record or setting is provided with a hostname such as .DKIM for Cloudflare Email Routing:
When you enable DKIM for your domain in the Cloudflare dashboard,
cf-xxxxxxxx._domainkeya dedicated CNAME record in the format is issued.
【DNS Registration Example】
# XSERVER's DKIM record (existing)
default._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCg..."
# Cloudflare Workers SendEmail DKIM record (newly added)
cf-xxxxxxxx._domainkey.example.com. IN CNAME dkim.cloudflare.com.By separating the selectors in this way, emails sent from XSERVER are signed and verified with XSERVER's key, and emails sent from Cloudflare Workers are signed and verified with Cloudflare's key, allowing for complete coexistence.
4. DMARC Policy Formulation and Alignment
DMARC (Domain-based Message Authentication, Reporting, and Conformance) is a policy that verifies SPF and DKIM authentication results and prevents sender domain spoofing.
Since 2024, major email providers such as Google (Gmail) and Yahoo! have mandated DMARC declaration for senders from custom domains.
| Record Type | Hostname | Value | Notes |
|---|---|---|---|
| TXT | _dmarc | v=DMARC1; p=quarantine; rua=mailto:dmarc-reports@example.com; pct=100; adkim=r; aspf=r | DMARC Policy Declaration |
p=none: Monitoring mode (it is recommended to start here and, after reviewing reports, escalate toquarantineorreject).p=quarantine: Emails that fail authentication are quarantined to the spam folder.rua: Recipient address for DMARC aggregate reports.
If both XSERVER and Cloudflare Workers correctly satisfy SPF/DKIM, emails sent via either path will pass DMARC alignment (Header From and Envelope From / DKIM d= match), resulting in DMARC: PASS.
Cloudflare Workers (Wrangler) Setup and Implementation
Once the DNS record design is complete, we proceed with the Cloudflare-side configuration and Workers code implementation.
1. Verification of Sender Address (Destination / Authorized Address)
Open "Email Routing" > "Settings" in the Cloudflare dashboard.
- Destination addresses:
Register and authenticate the address that the system is authorized to send to (or the administrator address for receiving test emails). With the free Email Routing plan, sending freely to unverified external addresses may be restricted.
- Unlocking Sending for Workers Paid Plan:
With a Cloudflare Workers Paid account, you can send system emails to any destination email address by submitting an unlock request from the dashboard.
2. Defining Bindings in the Wrangler Configuration File
Add an send_email binding to your Workers project's wrangler.jsonc (or wrangler.toml).
For wrangler.jsonc:
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "system-mail-worker",
"main": "src/index.ts",
"compatibility_date": "2026-11-01",
"send_email": [
{
"name": "SEND_EMAIL",
"destination_address": "admin@example.com", // Default or fallback destination
"allowed_destination_addresses": ["*@*"] // Allow sending to any destination (subject to account permissions)
}
]
}For wrangler.toml:
name = "system-mail-worker"
main = "src/index.ts"
compatibility_date = "2026-11-01"
[[send_email]]
name = "SEND_EMAIL"
allowed_destination_addresses = ["*@*"]3. MIME Message Construction and Sending Implementation with TypeScript
The Workers SendEmail binding accepts and sends raw MIME-formatted message strings. To safely generate email headers compliant with RFC 5322 and multipart (text/HTML) messages, it is recommended to use lightweight libraries such as create-mime-message and mime-tools.
pnpm add create-mime-messageTypeScript Implementation Example (src/index.ts):
import { createMimeMessage } from "create-mime-message";
export interface Env {
SEND_EMAIL: SendEmail;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if (request.method !== "POST") {
return new Response("Method Not Allowed", { status: 405 });
}
try {
const body = await request.json() as { to: string; subject: string; message: string };
// 1. Construct MIME message
const msg = createMimeMessage();
// Sender: Specify the address of a domain that has passed SPF/DKIM via DNS
msg.setSender({ name: "System Notification", addr: "noreply@example.com" });
// Recipient
msg.setRecipient(body.to);
// Subject
msg.setSubject(body.subject);
// Body (plain text)
msg.addMessage({
contentType: "text/plain",
data: body.message,
});
// 2. Send using Cloudflare SendEmail binding
// Construct and send a raw message object
const rawEmail = new EmailMessage(
"noreply@example.com", // Envelope-From (Return-Path)
body.to, // Envelope-To
msg.asRaw() // RFC-compliant MIME message string
);
await env.SEND_EMAIL.send(rawEmail);
return new Response(JSON.stringify({ success: true, messageId: msg.getMessageId() }), {
headers: { "Content-Type": "application/json" },
});
} catch (err: any) {
return new Response(JSON.stringify({ error: err.message }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
},
};Verification Steps and Troubleshooting
After completing the setup, strict verification will be performed using the following steps before going live.
1. Test sending to Gmail, etc., and email header verification
Send one email from Workers to a test account like Gmail.
From the menu in the top right of the received email (vertical 3-dot icon), select "Show original" and check the authentication results.
Expected Verification Results:
SPF: 'PASS' (domain example.com, IP address xxx.xxx.xxx.xxx)
DKIM: 'PASS' (domain example.com, selector cf-xxxxxxxx)
DMARC: 'PASS'- Confirm that all three items—SPF, DKIM, and DMARC—are PASS.
- Similarly, send an email to Gmail from Xserver's mailer (Thunderbird, webmail, etc.), and confirm that it also
default._domainkeypasses through.
2. Xserver normal reception test
Send a test email from an external email address (personal smartphone or account on a different domain) to the company's main address (info@example.com etc.).
- Confirm that the email arrives in the Xserver inbox without delay.
- This proves that the MX record continues to correctly point to Xserver and that no reception issues are occurring.
3. Common troubles and solutions
| Trouble | Cause | Solution |
|---|---|---|
| "DNS misconfigured" warning persists in Cloudflare dashboard | Cloudflare detects incomplete reception configuration because MX records point to Xserver | This is normal behavior. If you are only using it for sending, you can ignore it. Be careful not to carelessly click "Add records automatically." |
SPF: PermError occurs when sending to Gmail | More than one SPF record is registered in the DNS TXT record | Organize existing TXT records and ensure that the v=spf1 ... line is integrated into a single TXT record. |
EmailMessage error occurs when sending 550 Destination address not allowed | Destination limit for free plan, or unverified sender address | Check the sender address in Cloudflare Email Routing and, if necessary, confirm the unlock status of Workers Paid. |
| Bounce emails (undeliverable notifications) are not received or get lost | The address set in Envelope-From does not have a recipient | Confirm that the new EmailMessage('noreply@example.com', ...) address of noreply is receivable on the Xserver side (or has an alias/forwarding set up). |
Summary: Design Checklist for Coexistence Operations
This checklist summarizes the key points for allowing existing business emails on XSERVER and system emails sent from Cloudflare Workers to coexist on the same domain.
【Design and Configuration Checklist】
□ 1. Is the root domain's MX record maintained by Xserver, and has no Cloudflare MX been added?
□ 2. Is the SPF record (TXT) consolidated into one line, including both Xserver and Cloudflare (include:_spf.mx.cloudflare.net)?
□ 3. Are different selector names used for DKIM records on the Xserver side and the Cloudflare side?
□ 4. Is the DMARC record (_dmarc TXT) registered, and is the alignment policy defined?
□ 5. Is the send_email binding correctly defined in wrangler.jsonc / wrangler.toml?
□ 6. Has it been confirmed through header verification in Gmail, etc., that both Xserver and Workers transmissions pass SPF/DKIM/DMARC?
□ 7. Has it been tested that regular business emails from external sources can be successfully received by Xserver?Email infrastructure is the lifeline of a company, and even a single delivery failure can have a significant impact on business operations and credibility. By correctly distinguishing between sending (SPF/DKIM) and receiving (MX) protocol boundaries, and logically combining selector separation and SPF merging, you can safely enjoy the benefits of modern edge serverless sending while protecting your existing stable mail server.


