The developer's guide to sending physical letters from code.
1/9/2026As software engineers, we have spent the last fifteen years turning nearly every physical business process into code.We replaced corporate bank tellers with Stripe API calls. We replaced on-premise telecommunication PBX switches with Twilio REST requests. We replaced physical filing cabinets with Amazon S3 buckets, and we replaced postal delivery couriers with SendGrid email endpoints.Yet, for thousands of engineering teams across the United Kingdom, one critical business operation remains stubbornly, painfully trapped in the analog dark ages: sending physical letters.Every week, when customer service notices, statutory arrears letters, Section 21 eviction demands, court summonses, or high-value contracts need to be served, the digital pipeline grinds to an abrupt halt. An office worker or engineering intern is forced to download PDFs, walk over to an office printer, fight paper jams, manually fold sheets into thirds, stuff them into DL window envelopes, lick stamps or run them through a leased franking machine, and drop them into a red postbox on the street.The operational absurdity is staggering. In an era where modern cloud applications deploy to Kubernetes clusters in seconds, our physical communication infrastructure operates with 19th-century manual friction. Engineering leaders pull their hair out trying to connect automated billing and CRM databases to physical letterboxes, while developers are forced to write clunky local printer drivers or deal with legacy mailing houses requiring minimum order commitments of 10,000 sheets and seven-day turnaround times.Philosophically, sending a physical letter in the UK should be as simple, instantaneous, and programmatic as sending an email or an SMS. A developer should be able to send a single HTTP POST request containing a JSON address payload and an HTML document, and have it printed on heavy FSC-certified paper, inserted into an envelope, and handed to Royal Mail within 24 hours.At LetterAPI, we built the cloud-native postal infrastructure we always wished existed. We abstracted away the industrial digital presses, folding machines, Royal Mail Mailmark barcode encoders, and postal logistics into a clean, developer-friendly REST API. In this comprehensive technical guide, we walk you through everything an engineer needs to know to send physical letters programmatically: authentication, REST endpoints, PDF upload signatures, DL window address geometry, and real-time delivery webhooks.
The developer's mental model: How cloud-to-letterbox architecture works
To build reliable postal software, developers must understand the physical pipeline behind the API.When your application makes an HTTP POST request to LetterAPI, your JSON payload triggers an automated physical fulfillment pipeline:1. Address Parsing and PAF Validation: Our intake engine parses the recipient's address lines and queries the Royal Mail Postcode Address File (PAF) database containing over 30 million verified UK delivery points. Any minor typos or formatting errors are standardized.2. Document Pre-Flight and PDF/X Rendering: If you submit raw HTML, our headless rendering engine compiles it into a press-ready PDF at 1200 DPI. If you submit a pre-rendered PDF, our validation layer checks that the address block aligns with the DL envelope window aperture and verifies that colors are mapped to CMYK Fogra39 specifications.3. 2D Mailmark Barcode Injection: Our engine dynamically encodes Royal Mail's proprietary 2D Mailmark barcode onto the document, embedding the delivery class, destination sorting office, and unique tracking identifier.4. Industrial Digital Printing: At 4:00 PM UTC daily, jobs are batched to our high-speed commercial digital production presses. Documents are printed on FSC-certified 90gsm white wove paper.5. Automated Envelope Insertion: Automated vacuum-folding blades fold each document into thirds and insert it into a standard DL window envelope.6. Royal Mail Hub Injection: Envelopes are collected by Royal Mail distribution trucks and injected directly into the regional sorting center for First Class (next business day) or Second Class (2-3 business days) delivery.7. Webhook Telemetry: As the letter is scanned by Royal Mail sorting machinery and loaded for delivery, LetterAPI emits real-time webhooks back to your application.The 3-step plan: From zero to your first dispatched letter in 5 minutes
Getting started with LetterAPI is designed to be completely frictionless. Follow our 3-step plan:Step 1: Obtain your sandbox API key. Sign up at `letterapi.uk` and generate a test API key with zero upfront costs or credit card requirements. In sandbox mode, you can generate letters, test address validation, and inspect PDF proofs without printing a single sheet.Step 2: Construct your JSON dispatch payload. Format your recipient address according to UK postal conventions and supply your document content as either an HTML template string or a public PDF URL.Step 3: Execute the HTTP POST request. Send the request to `https://api.letterapi.uk/v1/letters`. Verify the instant JSON response containing your unique `letter_id`, estimated delivery date, and cost breakdown.Technical blueprint: Sending a physical letter via cURL and Node.js
Here is the fundamental HTTP request using cURL to dispatch a physical letter via LetterAPI:Here is the equivalent implementation in modern TypeScript using axios:Terminal — bashcurl -X POST https://api.letterapi.uk/v1/letters \-H "Authorization: Bearer test_sec_9938b827e8a9f02938472910" \-H "Content-Type: application/json" \-H "Idempotency-Key: job_ord_849204810" \-d '{"recipient": {"name": "Sarah Jenkins","company": "Apex Financial Ltd","address_line1": "100 Bishopsgate","address_line2": "Floor 14","city": "London","postcode": "EC2N 4AG","country": "GB"},"template_html": "<html><body><h1>Statutory Annual Review</h1><p>Dear Sarah, your account statement is ready.</p></body></html>","postage_class": "first_class","color": true,"double_sided": false}'
src/send-letter.ts — typescriptimport axios from 'axios';interface LetterResponse {id: string;status: 'created' | 'validating' | 'queued_for_print';recipient: {formatted_address: string[];paf_verified: boolean;};cost: {currency: string;print: number;postage: number;total: number;};estimated_delivery: string;created_at: string;}export async function sendPhysicalLetter(): Promise<LetterResponse> {const payload = {recipient: {name: 'Alexander Wright',company: 'Pinnacle Logistics UK',address_line1: '45 Oxford Street',city: 'Manchester',postcode: 'M1 4EE',country: 'GB'},template_html: `<!DOCTYPE html><html><head><style>@page { size: A4; margin: 20mm; }body { font-family: 'Helvetica Neue', Arial, sans-serif; color: #0f172a; line-height: 1.5; }.address-block { margin-top: 15mm; margin-bottom: 25mm; font-size: 11pt; }.brand { font-size: 18pt; font-weight: bold; color: #0284c7; border-bottom: 2px solid #0284c7; padding-bottom: 8px; }.content { margin-top: 20px; font-size: 10.5pt; }</style></head><body><div class="address-block"><strong>Alexander Wright</strong><br/>Pinnacle Logistics UK<br/>45 Oxford Street<br/>Manchester<br/><strong>M1 4EE</strong></div><div class="brand">PINNACLE AUDIT VERIFICATION</div><div class="content"><p>Dear Mr. Wright,</p><p>This letter confirms that your annual compliance audit has been formally registered with the UK Department for Business and Trade.</p><p>Enclosed in your online portal is your verified digital certificate.</p></div></body></html>`,postage_class: 'first_class',color: true,double_sided: false,metadata: {internal_audit_id: 'AUD-2026-9921'}};const response = await axios.post<LetterResponse>('https://api.letterapi.uk/v1/letters',payload,{headers: {'Authorization': `Bearer ${process.env.LETTERAPI_API_KEY}`,'Content-Type': 'application/json','Idempotency-Key': `dispatch_${Date.now()}`}});console.log(`Letter created successfully! ID: ${response.data.id}`);console.log(`PAF Verified: ${response.data.recipient.paf_verified}`);console.log(`Estimated Delivery: ${response.data.estimated_delivery}`);return response.data;}
Understanding Royal Mail DL window envelope geometry
One of the most frequent mistakes developers make when formatting letters is placing the recipient address in the wrong location.Unlike emails where the recipient is defined in metadata headers, a physical letter is folded into thirds and inserted into a DL window envelope. The recipient's physical address must appear through the clear cellophane window aperture.If the address block is offset by even 5mm, Royal Mail's automated optical character recognition (OCR) sorting machines cannot scan the address. The letter is flagged for manual sorting, causing significant delivery delays.LetterAPI enforces strict geometric requirements on your template:Top Margin Offset: The address block must start exactly 40mm down from the top edge of the A4 sheet.Left Margin Offset: The address block must start exactly 20mm in from the left edge of the sheet.Aperture Bounding Box: The entire address block must fit within a box measuring 90mm wide by 45mm tall.No Intrusion Zone: No corporate logos, return addresses, or decorative borders may appear within this 90mm x 45mm bounding box. Only the recipient's name, company, thoroughfare, town, and postcode are permitted.Listening to real-time delivery webhooks: Building reactive systems
A major superpower of LetterAPI is turning physical postal delivery into a real-time event-driven software architecture.Through native webhooks, your application can listen to key lifecycle milestones as the letter transitions through our production facility and the Royal Mail network:`letter.created`: The letter payload was validated and queued in our distributed intake pipeline.`letter.printed`: The letter was manufactured on commercial digital presses at 1200 DPI and folded into its envelope.`letter.dispatched`: The letter was handed over to Royal Mail logistics at our regional distribution hub.`letter.in_transit`: Royal Mail scanning machines recorded the envelope passing through a regional sorting mail center.`letter.delivered`: The letter arrived at the local delivery office and was loaded onto the postman's delivery route for final drop-off.`letter.failed`: An address validation or rendering error occurred, with actionable error diagnostics provided in the JSON payload.By subscribing to these webhooks, your system can automatically trigger follow-up SMS reminders, update CRM lead stages, alert Customer Success managers via Slack, or log legal service audit timestamps in your audit database.The unit economics: Transparent, pay-as-you-go pricing
Legacy mailing houses force software companies into predatory commercial contracts: minimum monthly spending commitments of £1,000+, setup fees of £500, complex volume tiering, and hidden machine setup surcharges.LetterAPI operates on pure cloud utility economics: transparent, pay-as-you-go pricing with zero setup fees, zero monthly minimums, and zero hardware maintenance contracts.A standard black-and-white single-sided letter delivered via Royal Mail Second Class costs just £0.86 all-inclusive—including 90gsm paper stock, DL window envelope, automated insertion, and Royal Mail postage.A full-color single-sided letter delivered via Royal Mail First Class (next business day delivery) costs £1.24 all-inclusive.Whether you send one letter a month or fifty thousand letters a day, your pricing is completely predictable and transparent, with itemized invoice breakdowns accessible via API and dashboard.The failure stakes: What happens when teams rely on manual office post
Consider the commercial and operational cost of maintaining manual office mailing routines.Highly paid operations staff, paralegals, or customer support representatives waste 10 to 15 hours every week printing invoices, folding paper, and queuing at the post office.Human errors inevitably creep in: wrong letters are stuffed into wrong envelopes, creating severe UK GDPR data breach liabilities under ICO scrutiny. Unvalidated addresses bounce back weeks later, while critical statutory notices miss legal deadlines.Your company spends thousands of pounds on office printer leasing, toner cartridges, franking machine maintenance fees, and administrative labor—all for an archaic, unscalable process that provides zero tracking or delivery visibility.The success transformation: Complete postal automation through code
Now envision your organization powered by LetterAPI's programmatic cloud postal infrastructure.Your developers integrate physical letter dispatch in an afternoon with clean, type-safe code. Critical business events—billing failures, legal notices, VIP onboarding, tenant circulars—automatically trigger physical correspondence with sub-second API latency.Every letter is manufactured with flawless industrial precision on FSC-certified paper, validated against Royal Mail PAF databases, and tracked in real time via Mailmark webhooks.Administrative postroom overhead is permanently eliminated, saving your business hundreds of hours and thousands of pounds every year, while transforming physical mail into a high-converting, reliable, and compliant digital channel.Stop treating physical mail like a 19th-century chore. Build modern, programmatic cloud-to-letterbox infrastructure with LetterAPI today.Automating document generation pipelines: Headless Chrome vs Weasyprint vs raw HTML
When integrating physical mail into your software platform, one of the first architectural decisions is where and how documents are rendered into PDFs.Developers typically evaluate three distinct rendering architectures:1. Local Headless Chromium (Puppeteer/Playwright): Running headless Chrome locally gives you full modern CSS and JavaScript support, including Flexbox and CSS Grid. However, Chrome is a notorious resource hog: each browser instance consumes 150MB to 300MB of RAM, and concurrent rendering easily triggers Linux OOM killer crashes on small cloud servers.2. Python/C-based engines (WeasyPrint/wkhtmltopdf): WeasyPrint provides excellent W3C Paged Media support without a heavy browser runtime. However, it lacks support for modern CSS Flexbox, renders complex fonts slowly, and requires heavy system-level C libraries (Pango, Cairo) that complicate Docker container builds.3. LetterAPI Server-Side HTML Rendering: LetterAPI eliminates this rendering dilemma entirely. By accepting raw HTML/CSS strings directly in the JSON payload, our cloud infrastructure renders your documents using distributed, horizontally auto-scaled worker fleets. You write standard HTML and CSS without managing browser instances or C libraries, enjoying sub-second API responses and flawless 1200 DPI vector PDF output.Security architecture: API authentication, HMAC request signatures, and credential rotation
In high-scale enterprise environments, securing programmatic postal endpoints is paramount.Because sending physical mail incurs financial costs and creates real-world legal notices, unauthorized access to your API keys could result in fraudulent mailings or data leakage.LetterAPI enforces rigorous security standards across all environments:Secret Key Scoping: LetterAPI provides distinct API keys for sandbox (`test_sec_...`) and production (`live_sec_...`) environments. Sandbox keys are restricted to virtual PDF proofs, preventing accidental production print runs during local testing.IP Whitelisting and CIDR Restraints: Enterprise accounts can restrict API key usage to authorized production server IP addresses or VPC CIDR blocks, preventing compromised keys from being used outside your infrastructure.Automated Credential Rotation: Our dashboard supports zero-downtime key rotation. You can generate a secondary active key, update your production environment secrets, and revoke the legacy key with zero API downtime.Handling Royal Mail delivery classes: First Class vs Second Class vs Tracked 24/48
Selecting the appropriate postage class allows engineering teams to optimize delivery speed against unit economics.LetterAPI supports the complete suite of Royal Mail commercial postal tiers:Second Class (Economy Default): Dispatched at £0.86 all-inclusive. Delivered within 2 to 3 business days across the entire United Kingdom. Ideal for non-urgent transactional correspondence: monthly invoices, utility bills, routine statements, and marketing mailings.First Class (Priority Next-Day): Dispatched at £1.24 all-inclusive. Aims for next working day delivery (Monday to Saturday) across 93% of UK postcodes. Essential for time-sensitive communications: overdue dunning notices, statutory court warnings, contract expirations, and executive VIP outreach.Every letter dispatched through LetterAPI—regardless of class—features a 2D Mailmark barcode, providing automated sorting verification and real-time delivery telemetry.Multi-tenant letter dispatch: Metadata tagging and sub-account billing for SaaS platforms
If you are building a B2B SaaS platform (such as a practice management system for accountants, property management software for estate agents, or an ERP for legal firms), your application needs to dispatch mail on behalf of thousands of distinct client organizations.LetterAPI provides built-in multi-tenancy support through flexible metadata tagging and sub-account routing.In every API request, developers can attach up to 50 key-value pairs in the `metadata` object (e.g. `tenant_id`, `client_code`, `invoice_id`).These metadata attributes are indexed in real time, allowing your billing engine to generate itemized monthly postal expenditure reports per client organization. You can pass through postal costs directly to your tenants, apply software markups, and reconcile billing without writing complex custom ledger tables.Handling international mailings: Royal Mail International Standard and Tracked services
While the vast majority of programmatic mail is delivered domestically within the United Kingdom, global software businesses frequently need to dispatch letters to cross-border recipients: international shareholders, overseas property owners, or foreign suppliers.LetterAPI provides native international dispatch across more than 190 countries worldwide via Royal Mail International Priority.When dispatching internationally, developers simply specify the ISO 3166-1 alpha-2 country code in the recipient payload (e.g. `country: 'US'`, `country: 'DE'`, `country: 'FR'`).LetterAPI's automated intake pipeline validates foreign postal formats, handles customs declaration documentation where applicable, and injects international airmail barcodes. Deliveries reach Western Europe within 3 to 5 business days and North America within 5 to 7 business days, providing global reach through a single unified API.The developer quick-reference: Best practices for high-velocity postal engineering
To summarize the developer guide, here are five non-negotiable architectural best practices for building physical mail systems:1. Always specify an Idempotency-Key header: Never dispatch letters without a deterministic, domain-specific idempotency key to prevent accidental duplicate printing during network retries.2. Validate addresses locally before API submission: Ensure postcodes conform to UK regex patterns and verify addresses against Royal Mail PAF to prevent 422 delivery exceptions.3. Respect Royal Mail DL window coordinates: Maintain a 20mm left margin, 40mm top margin, and 5mm quiet zone to ensure 100% optical sorting compliance.4. Decouple API dispatch from web request lifecycles: Use asynchronous background queues (BullMQ, Celery, SQS) to process mailings without degrading user experience.5. Verify cryptographic signatures on webhooks: Protect your webhook listener endpoints by validating HMAC SHA-256 signatures using constant-time comparison.The developer's deployment checklist: Going from sandbox to production in 10 minutes
Transitioning your letter dispatch pipeline from local development to production is simple and safe when you follow this checklist:First, verify that your production environment variables contain your live secret key (`live_sec_...`) stored securely in AWS Secrets Manager, HashiCorp Vault, or Doppler.Second, verify that your webhook listener URL uses TLS (HTTPS) with a valid SSL certificate, and confirm that your webhook signing secret is properly configured in your application secrets.Third, conduct an end-to-end smoke test by dispatching a single live letter to your company's own physical office address. Inspect the physical envelope when delivered by Royal Mail: verify the 90gsm paper weight, the sharpness of the 1200 DPI typography, and the exact centering of the address through the DL window aperture.Once physically confirmed, activate your automated billing or legal workflows. Your software is now directly connected to the UK physical letterbox network, running flawlessly on autopilot.LetterAPIPrint and post letters in the UK, from one letter to thousands.
© 2026 LetterAPI. All rights reserved.