Email receipt and invoice templates: a code-first guide for order and payment events
Email receipt and invoice templates built code first: define payload schemas, use HTML tables, add idempotency keys, prevent duplicates. This guide covers webhook handlers, TypeScript interfaces, React Email components, and structured markup so AI Overviews cite your template.
On this page
TL;DR: Receipt and invoice emails fail when the event payload, template markup, and retry logic are designed separately. Define your payment confirmation and invoice event payload schemas before writing any template markup. Use HTML tables for cross-client rendering reliability, type your React Email components with TypeScript interfaces, and always send an Idempotency-Key header when you call the send.io API to prevent duplicate sends when webhooks retry.
When a webhook retry fires, the same payment confirmation event arrives twice, and the customer gets two receipts for one payment. This guide treats the template, the event payload, and the retry logic as one system: define the payload schema first, build the template against that schema, then protect the whole flow with idempotency keys.
Required payload schemas for automated email flows
Every receipt and invoice email renders from a payload. If the payload schema is an afterthought, the template breaks every time the upstream service adds or renames a field. Define the schema before writing a single line of HTML.
Essential attributes in order.paid payloads
Receipt emails fire when a payment succeeds, not when an order is created. Standard practice gates receipt sends on a payment confirmation webhook from your payment processor, because order confirmation and payment capture are distinct triggers with different timing. Stripe sends the payment_intent.succeeded event when a payment succeeds, and the payload includes the PaymentIntent object with charge details and outcome metadata.
Your internal order.paid event (the one your order service publishes after confirming payment) should carry the fields your receipt template needs. Define the schema to include order identification, customer identity, line items, totals, and payment method details so the template never reaches outside the payload for data.
Decoding payment.succeeded webhook data
The payment processor's payment.succeeded event carries processor-level detail that your template needs but your order service might not store. Stripe's webhook payload for payment_intent.succeeded includes fields like amount_received, currency, and receipt_email. If the order payload lacks a customer email, expand latest_charge and read latest_charge.billing_details.email from the charge.
Map the processor payload to your internal schema rather than passing the raw object to your template. Your template should not know which processor handled the payment, because switching processors should require a transformation layer update, not a template rewrite.
Transforming event data for email rendering
Schema transformation converts external payloads into template-ready variables. Keep this layer thin and typed:
interface ReceiptTemplateData {
orderNumber: string;
customerName: string;
customerEmail: string;
items: Array<{ name: string; quantity: number; unitPrice: string; total: string }>;
subtotal: string;
taxAmount: string;
grandTotal: string;
currency: string;
paidAt: string;
paymentMethodSummary: string;
}
This interface decouples your template from any specific payment processor's event shape. If you switch processors, you update the transformation layer, not the template. The send.io provider compatibility layer accepts request formats from Resend, Postmark, SendGrid, Mailgun, Mailchimp, Brevo, and Mailjet, so the same transformation pattern works regardless of which API contract you migrate from. For a broader look at transactional payload structure, see the guide on how email APIs work.
Building reliable HTML receipt and invoice templates
A receipt or invoice template has to render the same totals table in Gmail, Outlook, and Apple Mail. The table-based receipt layout comes first, followed by the extra fields an invoice needs, tax compliance requirements, and accessibility.
Standardizing email receipt layouts
A receipt email follows a predictable structure: header, order summary, line items, totals, payment method, and footer. HTML tables remain the most reliable layout method because Outlook on Windows uses the Word rendering engine, which does not support CSS grid or flexbox consistently.
Here is a minimal receipt HTML template skeleton:
<table role="presentation" width="100%" border="0" cellspacing="0" style="max-width:600px;margin:0 auto;font-family:Arial,sans-serif;border-collapse:collapse;">
<tr>
<td style="padding:20px;background:#ffffff;">
<h1 style="margin:0;font-size:24px;line-height:30px;color:#111111;">Receipt for order #{{orderNumber}}</h1>
<p style="margin:8px 0 0;font-size:14px;line-height:20px;color:#555555;">Paid on {{paidAt}}</p>
</td>
</tr>
<tr>
<td style="padding:20px;">
<table width="100%" border="0" cellspacing="0" style="border-collapse:collapse;">
<tr style="border-bottom:2px solid #e5e5e5;">
<th align="left" style="color:#777;">Item</th>
<th align="right" style="color:#777;">Qty</th>
<th align="right" style="color:#777;">Price</th>
</tr>
<tr>
<td style="font-size:14px;">{{item.name}}</td>
<td align="right" style="font-size:14px;">{{item.quantity}}</td>
<td align="right" style="font-size:14px;">{{item.total}}</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding:20px;border-top:2px solid #e5e5e5;">
<table width="100%" cellspacing="0">
<tr><td>Subtotal</td><td align="right">{{subtotal}}</td></tr>
<tr><td>Tax</td><td align="right">{{taxAmount}}</td></tr>
<tr><td style="font-weight:bold;">Total</td><td align="right" style="font-weight:bold;">{{grandTotal}}</td></tr>
</table>
</td>
</tr>
</table>
Structuring invoice markup for events
An invoice email differs from a receipt in one critical way: it represents a payment request, not a payment confirmation. The header changes from "Receipt" to "Invoice," and the totals section includes a payment due date and status instead of a paid_at timestamp. Add these fields to your invoice payload schema:
- Invoice number: A sequential, unique identifier (legally required in the EU).
- Due date: When payment is expected.
- Payment terms: Net 30, due on receipt, or custom terms.
- Payment URL: A link to a hosted payment page or bank transfer details.
The line items and totals table structure carries over unchanged from the receipt template.
Required fields for tax compliance
If you sell to customers in the EU, Article 226 of the EU VAT Directive 2006/112/EC specifies up to 15 mandatory invoice particulars. The ones that affect your email template directly:
- Date of issue
- Sequential invoice number
- Supplier VAT identification number
- Customer VAT identification number (when applicable)
- Quantity and nature of goods or services
- Taxable amount per VAT rate
- VAT rate applied
- VAT amount due
Missing elements on an Article 226 invoice can invalidate the invoice for VAT reclaim purposes, meaning your EU business customers cannot deduct the VAT they paid you. Build these fields into your payload schema from the start, even if you do not sell in the EU today.
For US-based sole proprietors and Schedule C filers, IRS Publication 463 and IRC Section 274(d) require four core data points for business expense documentation: amount, date, place, and business purpose. For meal and entertainment expenses, the business relationship of the attendees is also required. Your receipt email covers the first three by default, so make sure the item descriptions provide the business purpose context.
Designing accessible receipt templates
Accessibility in email means semantic HTML, sufficient color contrast, and alt text on images. Receipt and invoice emails carry financial data that users rely on for expense reports and tax filing, so legibility matters more here than in marketing email.
- Use semantic table headers (
<th>elements) for line item columns so screen readers announce them correctly. - Set a readable font size for all text, including secondary details and footer copy. Neither the Web Content Accessibility Guidelines (WCAG) nor Section 508 of the Rehabilitation Act sets a minimum font size or specifies typefaces for email. Section 508 guidance describes typical email text as 10 to 11pt (13 to 15px), so treat 14px as a practical target rather than a firm requirement.
- Use a contrast ratio of at least 4.5:1 for text against its background.
- Avoid color-only indicators for payment status. Pair a green checkmark with the text "Paid" rather than relying on color alone.
Typed React Email components for receipts and invoices
React Email lets you write email templates as React components and render them to HTML strings. It compiles JSX components into table-based markup that renders consistently across Gmail, Outlook, and Apple Mail, because email clients reject modern CSS flexbox and grid layouts.
Typed interfaces for email receipts
TypeScript interfaces enforce the payload contract at compile time:
interface ReceiptEmailProps {
orderNumber: string;
customerName: string;
items: Array<{ name: string; quantity: number; unitPrice: string; total: string }>;
subtotal: string;
taxAmount: string;
grandTotal: string;
currency: string;
paidAt: string;
paymentMethodSummary: string;
}
Pass this interface to your React Email component, and the compiler catches missing fields before the template reaches production.
Defining TypeScript interfaces for invoices
The invoice component extends the receipt interface with payment-request fields:
interface InvoiceEmailProps extends ReceiptEmailProps {
invoiceNumber: string;
dueDate: string;
paymentTerms: string;
paymentUrl: string;
supplierVatId?: string;
customerVatId?: string;
}
The optional supplierVatId and customerVatId fields map to the EU VAT requirements from Article 226. For EU customers, these fields become required at runtime even though TypeScript marks them optional, because the compiler cannot know your customer's jurisdiction.
Transforming React into email HTML
React Email provides a render utility that converts your component tree into an HTML string suitable for sending via API:
import { render } from '@react-email/render';
import { ReceiptEmail } from './templates/ReceiptEmail';
const html = render(<ReceiptEmail {...templateData} />);
The html output is what you pass to your email API's html parameter. React Email transforms components into table-based markup with inline CSS, but you should still test the rendered output across email clients.
Mapping order status changes to email triggers
Each order status change should map to one template and one send call. Configure the webhook endpoint first, then the API parameters every send requires, then the handler patterns for order.paid and payment.succeeded events.
Configuring your webhook endpoint
Your order service publishes events when state changes. Your email service consumes those events and triggers the appropriate template. The webhook endpoint on your side receives the event payload, validates it, transforms it into template data, and calls the send API.
You configure webhook endpoints through the send.io API. send.io delivery, bounce, and complaint webhooks carry event metadata and failure diagnostics only, never message content.
Required API parameters for emails
Every transactional email send requires these parameters:
Parameter | Type | Description |
|---|---|---|
| string or string[] | Recipient email address(es) |
| string | Sender address on a verified domain |
| string | Email subject line |
| string | Rendered HTML body |
| HTTP header (string) | Client-generated deduplication key |
Optional parameters include reply_to, cc, bcc, headers, and tags for categorization. For receipt emails, set a descriptive from address like receipts@yourdomain.com rather than a generic noreply@ address, because customers reply to receipts with support questions.
Implementing the order.paid webhook
The webhook handler ties the event payload to the template render and the API call:
import { render } from '@react-email/render';
import { ReceiptEmail } from './templates/ReceiptEmail';
export async function handleOrderPaid(event: OrderPaidEvent) {
const templateData = transformOrderToReceipt(event.data);
const html = render(<ReceiptEmail {...templateData} />);
const idempotencyKey = `receipt-${event.id}`;
const response = await fetch('https://api.send.io/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SENDIO_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey,
},
body: JSON.stringify({
to: templateData.customerEmail,
from: 'receipts@yourdomain.com',
subject: `Receipt for order #${templateData.orderNumber}`,
html,
tags: ['receipt', templateData.orderNumber],
}),
});
if (!response.ok) throw new Error(`Send failed: ${response.status}`);
return response.json();
}
The idempotency key derives from the event ID, so if the same event arrives twice (because your webhook endpoint timed out and the order service retried), the second send attempt returns the original result instead of sending a duplicate receipt.
Handling payment.succeeded webhooks
The payment.succeeded handler follows the same pattern but uses a different template. With Stripe, the payment_intent.succeeded event arrives at your webhook endpoint, and your handler verifies the signature, extracts the Payment Intent object, transforms it into your internal receipt schema, then renders and sends.
The key difference is that the payment event might arrive before the order service finishes processing. Design your handler to check whether a receipt has already been sent for this order (using your own deduplication store or the idempotency key) before triggering a send.
Preventing duplicate receipts via idempotency
Webhook providers retry failed deliveries, so your handler will eventually receive the same event twice. Idempotency keys, event schema design, exponential backoff, and dead-letter queues together keep a retry from becoming a duplicate email.
Preventing double sends for invoices
Duplicate invoice emails damage customer trust. A customer who receives two identical invoices assumes a billing error, not a webhook retry.
The send.io Idempotency-Key header prevents this at the API level. The caller sets a client-generated key on each request. send.io stores it for 24 hours, and a retry with the same key returns the original result instead of sending a duplicate. This matches the industry standard: the Idempotency-Key header is defined in IETF draft standards. Because send.io stores keys for 24 hours, a retry after that window is processed as a new request.
A v4 UUID is the common choice for generating idempotency keys, suggested by both the IETF draft and Stripe. For receipt and invoice emails, deriving the key from the event ID (e.g., receipt-evt_1234) is more debuggable because you can trace the key back to the triggering event in your logs.
Designing idempotent invoice event schemas
Your event schema should carry a unique, stable event ID that survives retries:
interface InvoiceEvent {
id: string;
type: 'invoice.sent' | 'invoice.paid' | 'invoice.overdue';
created_at: string;
data: { invoice_id: string; customer_email: string; /* template fields */ };
}
The id field is your deduplication anchor. Use invoice-${event.id} as the Idempotency-Key header value. If your webhook endpoint receives the same event twice, both send attempts use the same key, and the second one returns the cached result.
Configuring exponential backoff for emails
If the send API returns a 5xx error, retry with exponential backoff. Client errors (4xx) should not retry because they indicate a problem with the request itself. Only retry on 5xx server errors and network timeouts, waiting progressively longer between attempts so a transient failure does not trigger a retry storm.
Setting up DLQs for payment emails
A dead-letter queue (DLQ) captures events that fail after all retry attempts, ensuring that a failed receipt send does not silently disappear.
- Enqueue on failure: After retry attempts are exhausted, push the event payload and error details to your DLQ (an SQS queue, a Redis stream, or a database table).
- Alert on DLQ depth: Set an alarm when the DLQ contains more than zero messages for payment-related events.
- Replay manually: After fixing the root cause, replay DLQ messages through the same handler. The idempotency key prevents duplicates if any messages were partially processed.
send.io delivery, bounce, and complaint webhooks tell you what happened after the send. Bounce events include the bounce type (Permanent or Transient), subtype, a human-readable message, and the per-recipient diagnostic code. If you send on send.io IPs, bounce events also include the raw SMTP response, the DSN code, and the sending IP. Route these webhook events to your monitoring pipeline so you can detect delivery failures before customers report them.
Testing your invoice and receipt render logic
A template that renders correctly in one client can break in another, and a handler that passes on a first delivery can fail on a retry. Simulating events, unit testing templates, and validating rendering across email clients catch both failures before production.
Simulating order and payment events
Test the full event-to-email pipeline locally before deploying. Build a test harness that publishes synthetic order.paid events to your webhook endpoint. Fire the test event at your webhook endpoint, verify the rendered HTML output, and check that the send API receives the correct parameters.
send.io provides framework-specific integration guides that cover webhook verification and sending from your framework of choice, including Next.js, Express, FastAPI, and Rails.
Unit testing your email templates
Unit tests for email templates validate the rendered HTML against expected content:
import { render } from '@react-email/render';
import { ReceiptEmail } from './templates/ReceiptEmail';
describe('ReceiptEmail', () => {
it('renders the order number and total', () => {
const html = render(<ReceiptEmail {...baseProps} />);
expect(html).toContain('ORD-001');
expect(html).toContain('22.00');
});
});
Run these tests in CI on every template change. A template that silently drops a field or misaligns a totals row is a production incident, not a style issue.
Validating cross-client email rendering
Outlook on Windows uses the Word rendering engine, which does not support CSS variables or @supports or complex flexbox. Apple Mail uses WebKit and scores highest on the Can I Email scoreboard. Gmail strips <style> blocks in some configurations.
Key constraints for receipt templates:
- max-width: Fully supported in Apple Mail, Gmail, and Yahoo Mail. Partially supported in Outlook (Windows versions 2003-2019 do not support it). Use fixed
widthattributes on table cells as a fallback. - CSS variables: Supported in Apple Mail only. Do not use them in receipt templates.
- Web fonts: Custom fonts via
@font-faceare supported in Apple Mail but not in classic Outlook, which falls back to Times New Roman. Use system font stacks (Arial, sans-serif) and treat web fonts as progressive enhancement.
Use a tool like Litmus or Email on Acid to preview your receipt template across clients before deploying. React Email abstracts much of this, but you should still verify the output, especially for Outlook.
Improving template markup for AI-driven indexing
AI Overviews and search engines can only cite template documentation they can parse. Invoice structured data, page structure for AI extraction, and canonical tags for syndicated copies make that documentation parseable.
Defining schema for invoice templates
If you publish your receipt or invoice templates on a documentation page, add structured data so AI Overviews and search engines can parse and cite them. Schema.org defines the Invoice type as "a statement of the money due for goods or services; a bill" with properties including totalPaymentDue, paymentDueDate, and provider.
Embed JSON-LD markup in your template documentation page with the Invoice type, a description, and the key properties your template renders. The partOfInvoice property in Schema.org's Order type indicates that an order is being paid as part of a referenced Invoice, which is useful when your documentation describes both order events and the invoices they generate.
Structuring payloads for AI indexing
AI Overviews extract information from pages that present structured, unambiguous content. For your template documentation page:
- Use descriptive headings that match developer search queries: "invoice email template" and "receipt HTML template" as H2 or H3 headings.
- Include the full template code in a copyable code block, because AI Overviews can cite code snippets directly.
- Label every field in a reference table with the field name, type, whether it is required, and a one-line description.
- Add a HowTo schema block alongside the Article schema, because the page describes a step-by-step process for building and deploying a template.
The goal is to make your page the authoritative source for email receipt and invoice templates so that AI Overviews cite your template rather than a generic small-business invoicing tool that lacks code examples.
Defining canonical tags for receipts
If you syndicate your template guide across multiple pages (a blog post, a docs page, and a GitHub README), set a canonical URL on each duplicate pointing to the primary version using a <link rel="canonical"> tag in the page head. Canonical tags prevent search engines from splitting authority across duplicate content, which means one URL accumulates all ranking signals and increases the likelihood that AI Overviews cite that URL.
Handling failed payment recovery flows
Not every payment succeeds, and not every successful charge stays final. The refund receipt and payment failure templates below each need their own payload fields.
Code-first refund receipt models
A refund receipt email confirms that a charge has been reversed. The template structure mirrors the payment receipt but with inverted amounts and a refund_reason field:
interface RefundReceiptProps extends ReceiptEmailProps {
refundId: string;
refundAmount: string;
refundReason: string;
originalOrderNumber: string;
refundedAt: string;
}
The refundAmount may differ from grandTotal for partial refunds. Display both the original total and the refunded amount in the totals table so the customer can reconcile the two.
Payment failure email templates
Stripe sends the payment_intent.payment_failed event when a payment fails. Your payment failure email template needs the failure reason, a retry URL where the customer can update their payment method, the amount that failed to process, and the next retry date if you use automatic retries.
The template copy should be direct: "Your payment of {{grandTotal}} for order #{{orderNumber}} was declined. Update your payment method to avoid service interruption." Include the retry URL as a prominent button, and do not bury the call to action below marketing content.
If your current email setup splits transactional sends and inbound routing across two providers, send.io handles both transactional sends and inbound routing under one API. You configure the webhook endpoint, send the receipt or invoice with an Idempotency-Key header, and receive delivery and bounce webhooks that tell you exactly what happened. The email templates and versioning feature lets non-engineers update receipt designs without touching application code, and the send.io provider compatibility layer accepts request formats from Resend, Postmark, SendGrid, Mailgun, Mailchimp, Brevo, and Mailjet, so migration typically requires only a base URL change for supported operations, not a full API rewrite.
Test the payment confirmation webhook flow with the send.io test addresses (delivered@send.io, bounced@send.io, complained@send.io, and suppressed@send.io) and a scoped API key.
FAQs
How do you prevent duplicate receipt emails when webhooks retry?
Set a client-generated Idempotency-Key header on every send request, derived from the triggering event's unique ID. send.io stores the key for 24 hours and returns the original result on retry instead of sending a duplicate.
What fields are legally required in invoice email templates?
In the EU, Article 226 of Directive 2006/112/EC requires up to 15 particulars including date of issue, sequential invoice number, supplier and customer VAT IDs, taxable amount per rate, VAT rate, and VAT amount. In the US, the IRS requires amount, date, place, and business purpose on expense receipts, plus the business relationship of attendees for meal and entertainment expenses.
Should you use HTML tables or divs for receipt email templates?
Use HTML tables. Outlook on Windows uses the Word rendering engine, which does not support CSS grid or flexbox consistently, while tables render reliably across all major email clients including Outlook, Gmail, and Apple Mail.
How do you test receipt templates across different email clients?
Use a preview tool like Litmus or Email on Acid to render your template across Outlook, Gmail, Apple Mail, and Yahoo Mail. Check max-width behavior in Outlook (partially supported) and avoid CSS variables (supported in Apple Mail only).
What's the difference between a receipt and an invoice email?
A receipt confirms that payment has been received and includes a payment timestamp and payment method details. An invoice requests payment and includes a due date, payment terms, and a payment call-to-action link.
Key terms glossary
Idempotency-Key: A client-generated HTTP header that prevents duplicate API operations when a request is retried. send.io stores the key for 24 hours and returns the original result on retry.
Dead-letter queue (DLQ): A holding queue for events that fail after all retry attempts. For payment emails, the DLQ captures failed receipt sends so they can be replayed after the root cause is fixed.
Webhook payload: The JSON body delivered to your endpoint when an event occurs (e.g., a payment confirmation). Contains event metadata and the data object your template consumes.
Scoped API key: An API key restricted to specific permissions or resources. send.io scoped keys carry permission lists and cannot grant permissions they do not hold.
Schema.org Invoice type: A structured data vocabulary for describing invoices on the web, with properties like totalPaymentDue and paymentDueDate. Used in JSON-LD markup to help search engines and AI Overviews parse invoice content.
Bounce diagnostic code: A per-recipient code in bounce webhook events that indicates why delivery failed. send.io bounce events include type (Permanent or Transient), subtype, a message, and the diagnostic code.