Skip to content
send.io
All posts

Invoice email template: line items, tax and PDF attachments

Invoice email template with line items, tax, PDF attachments, and fallback links that survive Gmail and Outlook filtering. Includes data schema, attachment size checks against 25MB limits, idempotency headers to prevent duplicate sends, and signed URLs for clients that strip PDFs.

On this page
TL;DR: An invoice email works when the line items, tax, and totals render correctly in the client and the PDF attachment actually arrives. Send both an HTML body with itemized data and a PDF attachment, plus a secure fallback link for clients that strip files. Check the base64-encoded size against Gmail's 25MB and Outlook's 20MB limits before you send. Use an Idempotency-Key header so retries don't generate duplicate invoices. If your encoded PDF exceeds 18MB, skip the attachment and send only the signed download link.

Invoice emails that render correctly in staging still fail in production when the PDF goes missing in the recipient's client or the tax total doesn't match the line items, usually because of MIME encoding, attachment size limits, and accounting schemas that store currency as floats or omit tax jurisdiction fields, details most invoice email templates ignore until they reach production.

Your invoice email has two jobs: present accounting-correct line items, tax, and totals in the body, and deliver a PDF attachment that survives mail client filtering. Both jobs fail when you treat the invoice as a simple HTML template and base64-encode a file onto it without handling MIME multipart structure and attachment size. This article walks through the data schema, MIME structure, attachment size limits, and fallback patterns that make invoice emails reliable. The code snippets call the send.io REST API directly at the https://api.send.io base URL, with no SDK required.

Invoice vs. receipt: accounting differences that matter

An invoice requests payment. A receipt confirms payment. The IRS requires a vendor-issued receipt for any single business expense of $75 or more (lodging always requires one, regardless of amount). Expenses under $75 still need a record showing the amount, date, place, and business purpose. An unpaid invoice can't serve as proof of settlement during an audit. This distinction drives when you send each document and what data each contains.

Timing your automated email flows

Send the invoice when you deliver the goods or complete the service, before payment arrives. Send the receipt after payment clears. If you send a receipt before payment, you've issued a document that claims a transaction happened when it didn't. For SaaS subscriptions, send the invoice at the start of the billing period. For one-time purchases, fire the invoice when the order ships. Trigger the receipt from your payment processor's webhook, not a timer.

Receipt timing and compliance rules

In many US jurisdictions, you can mark an invoice "PAID" with the payment date, method, and transaction reference to function as both invoice and receipt, but the paid invoice must clearly confirm settlement. If your system generates invoices and receipts from the same template, include a payment_status field that switches the document type and updates the language from "amount due" to "amount paid."

The IRS prefers original receipts for expenses over $75. If your customers need to expense their purchases, your receipt email needs the same line items, tax breakdown, and payment confirmation as the invoice, plus the payment method and transaction ID.

Tax rules for automated email invoices

Calculate tax in your application layer, not in the email template. Your template renders the calculated values but doesn't compute them. Your invoice data schema typically includes a tax_rate field (as a decimal, not a percentage string), a tax_amount field (typically the calculated tax in the smallest currency unit), and a tax_jurisdiction field (so you can audit why a specific rate was applied later).

Rounding mismatches between the HTML body and the PDF attachment create accounting discrepancies. Calculate the tax once, round it using your jurisdiction's rules (round half up, round half down, or banker's rounding), and store the rounded value in the database. Both the email body and the PDF read from the same stored value.

Structure your transactional invoice emails

You present the invoice data in a readable format that survives mail client HTML rendering. The structure needs to work in Outlook (which uses a Word-based rendering engine), Gmail (which strips some CSS), and Apple Mail (which has the most complete CSS support).

Optimizing HTML for email clients

Use table-based layouts, not CSS grid or flexbox, because Outlook's Word-based rendering engine doesn't support modern CSS layout methods. Inline all CSS styles because Gmail strips <style> tags in the <head>. Keep the total HTML size under 102KB because Gmail clips messages larger than that.

Structure the invoice as a series of tables: one for the header (invoice number, date, due date), one for the customer details, one for line items, and one for totals. Each table uses fixed widths (in pixels, not percentages) so Outlook doesn't collapse the layout.

Optimizing line item layout for delivery

Each line item needs a description, quantity, unit price, and line total. Format currency values with the correct symbol and decimal places for the invoice currency, not the customer's locale. If your customer is in Germany but you're invoicing in USD, show "$1,234.56" not "1.234,56 €".

There's no formal invoice schema standard that applies to every system, so treat the following fields as a suggested starting point, not a specification. Adjust them to your accounting and tax requirements before you write the send call:

Field

Type

Recommended

Description

invoice_number

string

yes

Unique identifier for the invoice. Sequential numbering is a common convention, but this schema doesn't enforce a format, so check your local accounting rules

customer_name

string

yes

Display name of the customer, commonly shown in the "Bill To" section. No formal standard requires this field, so adjust it to your accounting and tax requirements

customer_email

string

yes

Typically the address the invoice email is sent to. No formal standard requires this field, so adjust it to your delivery and accounting requirements

line_items

Array

yes

Typically a list of billable items, each commonly holding description, quantity, unit_price, and line_total. No formal standard sets the item fields, so match them to your accounting and tax requirements

subtotal

integer

yes

Typically the sum of the rounded line totals. No formal standard requires this field, and many systems store it as an integer in cents to avoid float rounding, so match the field and its format to your accounting system

tax_rate

Decimal

yes

Typically the applied rate as a decimal (e.g., 0.0825 for 8.25%) . No formal standard requires this field or its format, so adjust it to your jurisdiction's tax requirements

tax_amount

integer

yes

Typically the calculated tax in cents. No formal standard requires this field or its unit, so adjust it to your jurisdiction's tax requirements

total

integer

yes

Typically the subtotal plus tax in cents. No formal standard requires this field or its unit, so adjust it to your accounting and tax requirements

currency

String

yes

Typically an ISO 4217 code (e.g., "USD") . No formal standard requires this field or its format, so adjust it to your accounting and invoicing requirements

due_date

String

yes

Typically an ISO 8601 date. No formal standard requires this field or its format, so adjust it to your accounting and invoicing requirements

pdf_attachment

String

optional

Typically a Base64-encoded PDF. No formal standard defines this field or its encoding, so adjust it to your email provider's attachment format and your delivery requirements

pdf_url

String

optional

Typically a secure download link for the PDF, used as a fallback when the attachment is stripped or too large. No formal standard defines this field or its format, so adjust it to your storage setup and delivery requirements

Store currency amounts as integers in the smallest unit (cents for USD, pence for GBP) to avoid floating-point rounding errors. Convert to decimal display format only in the template rendering layer.

Rounding rules for invoice totals

Calculate each line item total as quantity * unit_price, round it, then sum the rounded line totals to get the subtotal. Calculate tax as subtotal * tax_rate, round it, then add it to the subtotal for the total. Rounding methods vary by jurisdiction. Within the US, each state sets its own rule: some round up to the nearest cent, some round down when the tax fraction falls below one-half cent, and states like Maryland require carrying the calculation to the third decimal place and rounding up only when that digit exceeds four. EU VAT rules can require rounding down. Store the rounding method in your tax configuration table, not hardcoded in the calculation function.

Strategies for serial number tracking

Invoice numbers should be unique and sequential so your records hold up in an audit and reconcile cleanly. Use a database sequence or an auto-incrementing integer, not a UUID. Format the number as INV-2026-00001 so it sorts correctly and includes the year for audit trails. Never reuse an invoice number, even if the send fails. If the email bounces, the invoice still exists in your accounting system with that number. If you need to resend, use the same invoice number and mark it as a duplicate send in your logs.

Building reliable invoice email workflows

Generate the PDF first, then build the email around it. The PDF attachment is the authoritative copy of the invoice, and the HTML body is a convenience rendering.

Generating invoice PDFs programmatically

Three libraries handle most HTML-to-PDF generation: Puppeteer (headless Chrome), ReportLab (Python native PDF), and wkhtmltopdf (WebKit-based converter). Each has different performance and rendering characteristics.

Performance is measured on warm instances with simple single-page invoices:

Library

Language

CSS Support

Generation Time

Memory per Instance

Puppeteer

Node.js

Full modern CSS

50-200ms warm (simple documents, pdf4.dev comparison). 48ms warm (2026 benchmark)

100-200MB per concurrent generation (peaks of 200-400MB reported)

Playwright

Node.js, Python

Full modern CSS

50-200ms warm (simple documents, pdf4.dev comparison); 3ms warm (simple documents, 2026 benchmark). 13ms in one complex-document benchmark

Similar to Puppeteer

ReportLab

Python

Limited (manual layout)

Fast (native)

Low

wkhtmltopdf

CLI wrapper

CSS 2.1, very limited CSS3 (Qt WebKit engine frozen circa 2012)

No published benchmark; test with your own template

Moderate

Puppeteer and Playwright both wrap the same Chrome DevTools Protocol, so render time for a given document is largely the same: Puppeteer and Playwright each render a simple A4 PDF in 50-200ms with a warm browser pool on a 2-core Linux VM. The 2026 pdf4.dev benchmark reports much lower warm times on simple documents, 3ms for Playwright and 48ms for Puppeteer, so treat the two sources as bounds of roughly 3-200ms rather than a single expected figure. Benchmarks on other documents show wider gaps. One benchmark of a complex PDF measured 13ms for Playwright and 58ms for Puppeteer on a warm instance. Results depend on document complexity and hardware, so benchmark your own invoice template before you pick a library for high-volume generation. For memory, plan for 100-200MB per concurrent Puppeteer generation. Its benchmark section lists 150-200MB per browser instance, and pdf4.dev reports peaks of 200-400MB, so set your concurrency limits against the upper end of that range. The same pdf4.dev benchmark lists wkhtmltopdf as deprecated and includes it for historical reference only, so it publishes no timings for it. If you still run wkhtmltopdf, measure generation time on your own invoice template.

For simple invoices with minimal styling, wkhtmltopdf works well and has lower memory overhead. For complex layouts with modern CSS, Puppeteer or Playwright give you full CSS support. ReportLab requires manual positioning but has no browser overhead.

If you're using Puppeteer, this pattern generates a PDF from your invoice HTML:

const puppeteer = require('puppeteer');

async function generateInvoicePDF(invoiceData) {
const browser = await puppeteer.launch();
const page = await browser.newPage();

const html = renderInvoiceHTML(invoiceData); // Your template function
await page.setContent(html);

const pdfBuffer = await page.pdf({
format: 'A4',
printBackground: true,
margin: { top: '20mm', right: '20mm', bottom: '20mm', left: '20mm' }
});

await browser.close();
return pdfBuffer;
}

Handling large invoice file attachments

When you base64-encode a PDF, the encoded data is about 33% larger than the original, per RFC 2045 Section 6.8. With MIME line wrapping (CRLF every 76 characters), the overhead reaches 36-37%. Your 10MB PDF becomes a 13.7MB attachment after encoding.

Check the encoded size against mail client limits before you send. Gmail limits attachments to 25MB for personal accounts. Outlook.com limits attachments to 20MB for free accounts and 25MB for Microsoft 365 commercial accounts, though Exchange administrators can raise the limit to 150MB.

Check your encoded attachment against these limits:

Mail Client

Attachment Size Limit

Notes

Gmail

25MB

Personal accounts, Workspace admin sets business limits

Outlook.com

20MB

Free accounts

Microsoft 365

25MB

Default, admin can raise to 150MB

Yahoo Mail

25MB

Standard limit


If your encoded PDF exceeds 18MB (leaving room for the HTML body and MIME headers), skip the attachment and send only the secure download link. Don't try to compress the PDF below the limit because compression adds processing time and doesn't guarantee the encoded size stays under the threshold.

Preventing blocked invoice attachments

Some corporate mail servers strip PDF attachments from inbound email as a security measure. Others quarantine messages with attachments for manual review. Include a secure download link in the email body, positioned prominently near the top. Use a signed URL with an expiration timestamp so the link doesn't become a permanent public file host. Make the link work even if the recipient forwards the email by not tying it to the recipient's email address or requiring login.

Handling Outlook and Gmail attachment issues

You'll find that mail clients don't handle attachments consistently. Gmail caps attachments at 25MB, but its PDF preview behavior isn't documented with a size threshold, so test how your invoice PDFs display instead of assuming a preview appears. Outlook on Windows shows a preview but blocks some file types by policy. Mobile clients often don't show previews at all.

Strategies for stripped PDF files

When a mail server strips the PDF attachment, the recipient sees the HTML body but no file. Always render the full line items, tax, and totals in the HTML body, even when you're attaching a PDF, so your customer has a complete invoice if the PDF disappears. Make the fallback link obvious by placing it in a button or prominent link near the top of the email, not buried in the footer. Use clear language: "Download PDF invoice" not "View document." Test the link in an incognito browser to confirm it doesn't require authentication.

Ensuring PDF access without attachments

Some high-volume senders skip the attachment entirely and send only a download link. This pattern reduces email size, eliminates attachment filtering issues, and gives you analytics on who downloads the invoice. The trade-off is that customers can't save the invoice directly from their email client. If you use this pattern, host the PDF on a domain you control with HTTPS. Set an expiration time on the signed URL that balances security with customer access needs, keeping in mind that AWS S3 presigned URLs have a maximum expiration of 7 days. Include the invoice number in the URL path so customer support can construct the link manually if needed.

How mail clients interpret invoice HTML

Outlook uses Microsoft Word's rendering engine for HTML email and doesn't support CSS floats, positioning, or most modern layout properties. Gmail strips <style> blocks and some CSS properties. Apple Mail has the most complete CSS support but still has quirks with web fonts. Use inline styles on every element, set explicit widths on table cells, and avoid CSS shorthand properties (use margin-top, margin-right, margin-bottom, margin-left instead of margin). Test in real clients, not just browser previews, because email client HTML rendering differs significantly from browser rendering.

Embedding PDFs in transactional invoice emails

The MIME structure for an email with a PDF attachment follows RFC 2045. Your message has a multipart/mixed content type with two parts: the HTML body (text/html) and the PDF attachment (application/pdf). RFC 3778 standardized application/pdf as the correct MIME type for PDFs (updated by RFC 8118).

Linking invoices to secure storage

Store generated PDFs in object storage (S3, Google Cloud Storage, or similar) with a lifecycle policy that retains them for your accounting compliance period (typically 7 years). Generate a signed URL at send time with an expiration timestamp. The signed URL grants temporary read access without requiring the recipient to authenticate.

Generate your signed URLs with this pattern:

const crypto = require('crypto');

function generateSignedURL(invoiceNumber, expiresInDays = 7) {
const expiryTimestamp = Date.now() + (expiresInDays * 24 * 60 * 60 * 1000);
const payload = `${invoiceNumber}:${expiryTimestamp}`;
const signature = crypto
.createHmac('sha256', process.env.URL_SIGNING_SECRET)
.update(payload)
.digest('hex');

return `https://invoices.example.com/download/${invoiceNumber}?expires=${expiryTimestamp}&signature=${signature}`;
}

Verify the signature and expiry timestamp in your download endpoint before serving the PDF. Log each download with the invoice number and timestamp so you have an audit trail of who accessed which invoice.

Don't include the customer's email address or account ID in the URL. If your customer forwards the invoice email to their accountant, the accountant needs to access the PDF without logging in as the customer.

Email template data schema

Your complete send call includes the invoice data, the base64-encoded PDF, the fallback link, and an Idempotency-Key header. send.io stores each Idempotency-Key for 24 hours and returns the original result on retry instead of sending a duplicate invoice.

Here's the complete send pattern with attachment size checking and idempotency protection:

const fetch = require('node-fetch');
const fs = require('fs');

async function sendInvoiceEmail(invoiceData, pdfBuffer) {
// Encode PDF to base64
const pdfBase64 = pdfBuffer.toString('base64');

// Check encoded size (RFC 2045 adds ~33% overhead)
const encodedSizeMB = (pdfBase64.length * 0.75) / (1024 * 1024);
const shouldAttach = encodedSizeMB < 18; // Leave room for HTML + headers

// Generate fallback download link
const pdfUrl = generateSignedURL(invoiceData.invoice_number);

// Render HTML body with line items
const htmlBody = renderInvoiceEmailHTML(invoiceData, pdfUrl);

const payload = {
from: 'billing@yourdomain.com',
to: invoiceData.customer_email,
subject: `Invoice ${invoiceData.invoice_number} from Your Company`,
html: htmlBody,
attachments: shouldAttach ? [{
filename: `invoice-${invoiceData.invoice_number}.pdf`,
content: pdfBase64,
content_type: 'application/pdf'
}] : []
};

// POST to the send.io emails endpoint
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': `invoice-${invoiceData.invoice_number}-${invoiceData.idempotency_token}`
},
body: JSON.stringify(payload)
});

if (!response.ok) {
const error = await response.json();
throw new Error(`Send failed: ${error.message}`);
}

return await response.json();
}

Format your Idempotency-Key to include the invoice number and a unique token (typically a UUID you generate when you first attempt the send). Store the token in your database with the invoice record. If the send times out or returns a 5xx error, retry with the same key. send.io returns the original send result without delivering a duplicate email.

If you omit the Idempotency-Key header, send.io has no deduplication protection. Your retry sends a duplicate invoice with the same invoice number, which creates confusion for the customer and reconciliation problems for your finance team. send.io's delivery event webhooks report bounce and delivery status per recipient. The bounce object includes the type (Permanent or Transient), subtype, a message, and the diagnostic code. On send.io's sending IPs, bounce events also include the sending IP, the raw SMTP response, and the DSN code. Use these diagnostics to update the invoice delivery status in your database and trigger a fallback notification (like an in-app alert) if the invoice email bounces.

Start by testing with the send.io test addresses and a sample PDF attachment. Send to the documented test addresses (delivered@send.io, bounced@send.io, complained@send.io, and suppressed@send.io) and verify delivery status in the API logs before you commit to a production integration.

FAQs

What's the maximum PDF attachment size for email?

Gmail allows 25MB for personal accounts, Outlook.com allows 20MB for free accounts, and Microsoft 365 defaults to 25MB but administrators can raise it to 150MB. After base64 encoding adds 33-37% overhead, keep your raw PDF under 13MB to stay under the 20MB Outlook.com limit.

Should the invoice be sent as an attachment or a link?

Send both. Attach the PDF for customers who expect to save it directly from their email client, and include a secure download link for customers whose mail server strips attachments. If your encoded PDF exceeds 18MB, send only the link.

How do you prevent invoice emails from landing in spam?

Configure DKIM, SPF, and DMARC records on your sending domain and keep your bounce rate low. send.io suspends accounts at documented thresholds: under 2,000 sends in a 30-day window, the cap is 15 hard bounces or 3 complaints. Above that volume, the threshold becomes rate-based, so check the limits that apply to your sending volume. Use a consistent "from" address (like billing@yourdomain.com) so recipients can whitelist it.

Can line items appear in both the email body and PDF?

Yes, and you should. The HTML body makes the invoice data visible without downloading the PDF, and the PDF provides the authoritative formatted copy. Generate both from the same data source so the values match exactly.

What invoice numbering format works best?

Use a sequential integer with a prefix and year, formatted as INV-2026-00001. Never reuse a number, even if the send fails. Whether sequential numbering is a legal requirement depends on the jurisdiction. It's required on VAT and GST invoices in the UK, the EU, and India. The US has no federal law requiring strictly sequential invoice numbers, but sequential numbering is standard practice, the default in most accounting software, and makes audit trails easier to follow. Check the rules for each jurisdiction you invoice in.

Key terms glossary

Base64 encoding: A binary-to-text encoding scheme that converts binary data (like a PDF) into ASCII characters for transmission over text-only protocols. It increases data size by approximately 33% per RFC 2045.

Idempotency-Key: A client-generated unique identifier you send as an HTTP header with an API request. The server stores the key and returns the original response if you send the same key again, preventing duplicate operations from retries.

MIME (Multipurpose Internet Mail Extensions): The standard that extends email to support non-text attachments, multipart messages, and non-ASCII character sets. Defined in RFC 2045.

application/pdf: The registered MIME content type for PDF documents, defined in RFC 3778 and updated by RFC 8118. Email clients use this type to determine how to handle the attachment.

Signed URL: A URL that includes a cryptographic signature and expiration timestamp, granting temporary access to a protected resource without requiring authentication. The signature proves the URL was generated by an authorized system.