Send your first physical letter from code in under 5 minutes.

9/11/2026
Send your first physical letter from code in under 5 minutes.

The developer epiphany: Bridging software bits and physical letterboxes

As software developers, we are accustomed to programmatic omnipotence.With three lines of code and an API token, we can provision a virtual server cluster in Frankfurt, process a multi-currency credit card payment through Stripe, send an SMS message across four continents via Twilio, or stream terabytes of analytics to Datadog.In the digital world, complexity has been abstracted into elegant REST interfaces and JSON payloads.Yet whenever an application needs to interact with the real, physical world—sending a formal legal warning, an urgent appointment card, a paper invoice, or a physical security token—developers have historically hit a brick wall.You search online for 'print and mail API UK', and instead of modern developer documentation and a self-serve signup screen, you are greeted by 1990s enterprise sales portals demanding: 'Book a 45-minute demo with our sales representative', 'Download our 60-page PDF integration specification', and 'Minimum contract value: £10,000 per annum.'If you somehow endure the enterprise sales process, the integration involves dumping tab-delimited CSV files onto an insecure SFTP server or manually emailing PDF attachments to an account executive.It feels archaic, fragile, and deeply frustrating.Sending a physical letter in the United Kingdom should not require weeks of enterprise negotiations.It should be as instantaneous, elegant, and frictionless as sending an HTTP POST request from your terminal.LetterAPI was built by software engineers who believe that physical mail should be a first-class citizen of the modern cloud stack.In this comprehensive guide, we will walk you from an empty command line to your first live, physical letter injected into the Royal Mail First Class network in under five minutes.

Prerequisites: What you need before making your first API call

To follow this tutorial, you do not need an enterprise contract, a credit card on file, or a corporate purchase order.You only need three things:1. Any standard terminal environment with `curl`, or a runtime environment for Node.js (v18+), Python (v3.9+), Go, or Ruby;2. A free LetterAPI developer sandbox account (created in under 30 seconds at `https://letterapi.uk/signup`);3. A valid UK postal destination address (or you can use our built-in synthetic test addresses).The moment you register your sandbox account, your dashboard generates two distinct API keys:- Sandbox Test Key (`test_key_...`): Allows you to send unlimited mock letters, simulate carrier delivery states, inspect generated vector PDF proofs, and trigger test webhooks without charging any balance or printing physical paper.- Production Live Key (`live_key_...`): Dispatches real, physical letters directly to our certified UK cleanroom production lines for next-day Royal Mail delivery at £0.86 flat.For this quickstart walkthrough, we will execute our requests using your sandbox key.

The 3-step programmatic postal workflow

Every physical letter dispatched through LetterAPI follows a clean, predictable three-step lifecycle:Step 1: Construct the JSON Payload.Define your recipient's postal address, select your delivery class (First Class or Second Class), and provide your document content—either as raw HTML/CSS, a registered template identifier with dynamic variables, or a pre-rendered PDF URL.Step 2: Dispatch via POST Request.Send an authenticated HTTP POST request to `https://api.letterapi.uk/v1/letters`. The API gateway validates the address against the Royal Mail Postcode Address File (PAF), lints your document layout, renders a vector PDF, and returns an HTTP 201 Created response within 150 milliseconds.Step 3: Track Real-Time Carrier Telemetry.Inspect the rendered vector PDF via the returned preview URL, or listen to automated webhook events as the envelope transitions through industrial cleanroom printing, folding, sealing, and Royal Mail 2D Mailmark carrier sorting.

Step 1: Your first letter via cURL (The 60-second test)

Open your terminal and execute the following cURL command, replacing `YOUR_TEST_API_KEY` with your sandbox API key:
Terminal (cURL Quickstart) — bash
curl -X POST https://api.letterapi.uk/v1/letters \
-H "Authorization: Bearer test_key_abc123xyz789" \
-H "Content-Type: application/json" \
-d '{
"recipient": {
"name": "Jane Doe",
"address_line_1": "10 Downing Street",
"city": "London",
"postcode": "SW1A 2AA",
"country": "GB"
},
"content": {
"type": "html",
"html": "<h1>Hello from code!</h1><p>This physical letter was dispatched using LetterAPI in under 5 minutes.</p>"
},
"postage": "first_class"
}'
Within 200 milliseconds, LetterAPI validates the address against the sovereign PAF database, compiles the HTML into a print-ready vector document, and returns an HTTP 201 JSON response:
Response (HTTP 201 Created) — json
{
"id": "let_8f92a1c4b7e3",
"status": "created",
"mode": "test",
"postage": "first_class",
"recipient": {
"name": "Jane Doe",
"address_line_1": "10 Downing Street",
"city": "London",
"postcode": "SW1A 2AA",
"paf_verified": true,
"delivery_point_suffix": "1A"
},
"cost": {
"amount": 0.86,
"currency": "GBP"
},
"preview_url": "https://api.letterapi.uk/v1/letters/let_8f92a1c4b7e3/preview.pdf",
"created_at": "2026-10-14T10:15:30.000Z"
}
Copy the `preview_url` into your browser: you will see the exact, pixel-perfect 1200 DPI vector PDF that will be printed on our physical digital presses, complete with recipient address aperture alignment.

Step 2: Idiomatic implementation in TypeScript / Node.js

For production microservices and backend applications, below is a clean, production-ready TypeScript implementation using standard fetch:
src/quickstart.ts — typescript
import fetch from 'node-fetch';
​
interface DispatchResponse {
id: string;
status: string;
preview_url: string;
cost: { amount: number; currency: string };
}
​
async function sendLetter(): Promise<void> {
const apiKey = process.env.LETTERAPI_KEY || 'test_key_abc123xyz789';
​
const payload = {
recipient: {
name: 'Dr. Alexander Wright',
address_line_1: '42 Baker Street',
city: 'London',
postcode: 'NW1 6XE',
country: 'GB'
},
content: {
type: 'html',
html: `
<div style="font-family: Arial, sans-serif; font-size: 11pt; color: #111;">
<h2 style="color: #0284c7; border-bottom: 2px solid #0284c7; padding-bottom: 8px;">
Account Security Notice
</h2>
<p>Dear Alexander,</p>
<p>Your password was successfully updated on <strong>14 October 2026 at 09:30 AM</strong>.</p>
<p>If you did not authorize this change, please contact our 24/7 security hotline immediately at <strong>0800 123 4567</strong>.</p>
<div style="margin-top: 30px; padding: 12px; background: #f0fdf4; border-left: 4px solid #16a34a;">
<strong>Verification Reference:</strong> SEC-99482-GB
</div>
</div>
`
},
postage: 'first_class',
options: {
double_sided: false,
color: true
},
metadata: {
user_id: 'usr_882910',
event_type: 'SECURITY_CREDENTIAL_CHANGE'
}
};
​
const res = await fetch('https://api.letterapi.uk/v1/letters', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
​
if (!res.ok) {
const err = await res.json();
throw new Error(`LetterAPI Error [${res.status}]: ${err.message}`);
}
​
const result = (await res.json()) as DispatchResponse;
console.log(`✓ Letter successfully dispatched! ID: ${result.id}`);
console.log(`✓ PDF Vector Proof: ${result.preview_url}`);
}
​
sendLetter().catch(console.error);
Run this script with `npx ts-node src/quickstart.ts`. Within a fraction of a second, your terminal logs the unique letter ID and visual proof URL.

Step 3: Idiomatic implementation in Python

For Python developers, data engineers, and Django/FastAPI applications, here is the equivalent implementation using the `requests` library:
quickstart.py — python
import os
import requests
​
def send_letter():
api_key = os.getenv("LETTERAPI_KEY", "test_key_abc123xyz789")
url = "https://api.letterapi.uk/v1/letters"
​
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
​
payload = {
"recipient": {
"name": "Sarah Jenkins",
"address_line_1": "14 Cathedral Close",
"city": "Salisbury",
"postcode": "SP1 2EF",
"country": "GB"
},
"content": {
"type": "html",
"html": """
<div style="font-family: Georgia, serif; line-height: 1.6;">
<h2>Notice of Annual Dividend Payment</h2>
<p>Dear Sarah,</p>
<p>We are pleased to confirm that your quarterly dividend of <strong>£142.50</strong> has been credited to your nominated bank account.</p>
<p>Attached to this statement is your tax voucher for your annual HMRC self-assessment records.</p>
</div>
"""
},
"postage": "first_class",
"options": {
"color": True
}
}
​
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
​
data = response.json()
print(f"✓ Letter created successfully! ID: {data['id']}")
print(f"✓ Vector PDF Proof: {data['preview_url']}")
​
if __name__ == "__main__":
send_letter()
Execute with `python3 quickstart.py` to trigger instantaneous document compilation.

Mastering DL window envelope geometry: Preventing address clipping and layout bleed

When designing physical letters, understanding physical paper geometry is essential.In the United Kingdom, standard business mail utilizes DL window envelopes.To ensure that your recipient address aligns perfectly through the clear envelope aperture without manual tweaking, follow the official LetterAPI DL layout specifications:- Paper Format: Standard A4 (210mm wide x 297mm high);- Window Aperture Dimensions: 90mm wide x 45mm high;- Window Aperture Position: Exactly 20mm from the left paper margin, and 40mm from the top paper margin.LetterAPI's vector compiler handles this automatically:When you submit an address object in your API payload, our rendering engine injects the recipient address into the exact coordinate sector on Page 1 of the generated PDF.The rest of your HTML content renders below the 95mm vertical mark on Page 1, ensuring zero visual overlap.If your document extends onto Page 2, the address aperture on subsequent sheets is automatically suppressed, giving your content the full printable area of the page.

Real-time webhooks: Subscribing to Royal Mail Mailmark delivery telemetry

In physical mail, software observability is critical.You should never have to wonder whether a letter was printed or when it will be delivered.LetterAPI provides an event-driven webhook architecture that streams real-time lifecycle updates directly to your backend servers:1. `letter.created`: Payload validated and accepted into the production queue.2. `letter.rendered`: Vector PDF compiled in volatile RAM; visual preview generated.3. `letter.printed`: Document printed on continuous digital press within our cleanroom facility.4. `letter.dispatched`: Envelope machine-folded, sealed, and handed over to Royal Mail wholesale sorting.5. `letter.sorted`: Envelopes scanned by Royal Mail 2D Mailmark optical sorting machines at the regional Mail Centre.6. `letter.returned_undeliverable`: Return-to-sender carrier telemetry captured if the recipient has moved or the address is vacant.Configuring webhooks takes seconds in your developer dashboard: provide your HTTPS endpoint URL, copy your HMAC signing secret, and verify incoming webhook signatures with our official SDK helper.

Simulating postal lifecycles in the developer sandbox

Developing against a physical postal service requires fast automated testing.You cannot wait two days for a postal carrier to test whether your webhook listener updates your database correctly.LetterAPI's developer sandbox includes synthetic simulation capabilities:- Fast-Forward Header (`X-Mock-Delivery-Speed: instant`): Passes through all six lifecycle events within five seconds of API dispatch.- Synthetic Address Triggers: Submitting postcodes starting with `TE57` triggers deterministic mock outcomes without consuming postage balance.- Undeliverable Simulation (`postcode: 'TE57 0BO'`): Simulates a 'Gone Away' return-to-sender event, allowing you to test your returned-mail recovery logic locally.This developer experience allows your team to test edge cases, error states, and asynchronous webhook pipelines in your continuous integration (CI) test suite before deploying to production.

Flipping the switch: Transitioning from sandbox to live production dispatch

Once you have verified your template layout, tested your webhook endpoints, and verified address alignment, launching into live production requires exactly one line of change:Swap your API key from your test key (`test_key_...`) to your live production key (`live_key_...`).That is literally all it takes.When an API call is made with your live key:- The request routes to our certified UK cleanroom production presses;- The letter is printed on premium 90gsm FSC-certified bond paper;- Machine-sealed in an opaque security DL window envelope;- Injected into Royal Mail First Class wholesale processing at 17:00 that exact same day;- Delivered through your customer's physical letterbox the following morning.With zero setup fees and flat £0.86 pricing, you have deployed an enterprise-grade national postal communications pipeline into production in an afternoon.

Advanced document layout techniques: CSS paged media, page breaks, and dynamic headers

When building professional multi-page business letters, understanding CSS Paged Media module specifications transforms your document formatting.LetterAPI's vector rendering engine provides full native support for modern CSS print standards:1. Controlling Page Breaks: Use `page-break-before: always;` or `break-before: page;` to force section breaks onto fresh sheets (ideal for separating executive summary letters from itemized invoices). Use `page-break-inside: avoid;` to prevent tables or signature blocks from awkwardly splitting across page boundaries.2. Dynamic Page Counters: Inject automated running page numbers into your CSS margins using standard CSS counters:`@bottom-right { content: 'Page ' counter(page) ' of ' counter(pages); font-size: 9pt; color: #64748b; }`3. Margin Boxes: Define running document titles, confidential warnings, and legal entity disclosures in `@top-left`, `@bottom-left`, or `@top-right` margin boxes.4. Window Envelope Safe Margins: Ensure your first page body content begins with `margin-top: 55mm;` to preserve clearance for the 20mm x 40mm DL window address aperture, while subsequent pages automatically reclaim full page height.Mastering these CSS paged media directives ensures that your documents render with the polish of professional desktop publishing software.

Handling multi-page PDFs and dynamic enclosures: Merging attachments and terms

Many transactional workflows require appending pre-existing PDF documents to your letter.For example, a debt collection notice may require appending a copy of the original signed credit agreement; an employment offer letter requires appending the standard staff handbook; or a healthcare appointment requires attaching a pre-printed clinic preparation brochure.Instead of forcing you to re-code complex existing PDFs into HTML, LetterAPI supports dynamic document merging:In your API payload, you can pass an `attachments` array containing URLs or base64 data strings of pre-rendered PDF documents:`"attachments": [ "https://storage.enterprise.co.uk/docs/terms_v4.pdf", "data:application/pdf;base64,JVBERi0..." ]`LetterAPI's ingestion pipeline validates the attachments, normalizes page dimensions to standard A4, and seamlessly collates the merged document into a single continuous print job.Our robotic inserters calculate the total page count dynamically, ensuring that multi-page booklets are inserted into appropriate envelope sizes with zero human intervention.

Security best practices: API key scoping, IP allowlisting, and webhook signature verification

When deploying programmatic mail in enterprise and regulated production environments, robust security hygiene is essential.LetterAPI provides granular security controls to protect your production dispatch pipeline:1. Granular API Key Scoping: In your developer dashboard, generate restricted API keys with minimal necessary privileges. For example, assign your customer support dashboard a read-only tracking key (`scope: letters:read`), while your billing microservice receives a dispatch-only key (`scope: letters:write`).2. IP Address Allowlisting: Restrict production API access to your application server static IP addresses or VPC CIDR blocks, preventing unauthorized API calls even if a secret key is accidentally leaked.3. Webhook Signature Verification: Never process webhook payloads without verifying their cryptographic authenticity. LetterAPI computes an HMAC-SHA256 signature using your secret webhook key and includes it in the `X-LetterAPI-Signature` header.Validate that `HMAC_SHA256(payload_body, webhook_secret) === header_signature` before executing state updates in your database, completely protecting your backend from webhook spoofing attacks.

Frontend integration: Powering address autocomplete and PAF cleansing in web forms

A common cause of postal dispatch failure is poor data quality entered by end users on registration and checkout forms.When users mistype their postcodes, omit flat numbers, or spell street names incorrectly, physical mail delivery is compromised.LetterAPI provides a high-speed frontend address lookup endpoint powered by the Royal Mail Postcode Address File (PAF):Integrate our lightweight JavaScript address autocomplete widget into your customer onboarding forms:As the user types their postcode, the widget queries `GET /v1/addresses/autocomplete?postcode=SW1A2AA` and returns a clean, structured dropdown of all matching delivery points in under 40 milliseconds.When the user clicks their address, the form automatically populates verified premise elements (premise name, sub-building, thoroughfare, postal town, and exact DPS code).Cleansing addresses at the moment of user entry eliminates up to 99% of postal delivery failures, guaranteeing that physical correspondence reaches the intended recipient on the first attempt.

Global reach: International postal dispatch across 190+ countries via Royal Mail International Priority

While UK domestic delivery represents the vast majority of our transactional volume, modern software platforms serve global customer bases.Whether you need to dispatch an equity award confirmation to an engineer in Munich, a formal regulatory notice to a shareholder in New York, or an invoice reminder to a supplier in Tokyo, LetterAPI provides native cross-border postal fulfillment across 190+ countries.To dispatch a letter internationally, simply supply the destination country's two-letter ISO 3166-1 alpha-2 code in the recipient object: `"country": "DE"` or `"country": "US"`.LetterAPI's address formatting engine immediately applies Universal Postal Union (UPU) S42 international address formatting rules, ensuring the country name is capitalized in English on the final envelope line and postal codes conform precisely to national postal conventions.All international correspondence is printed in our UK hub on premium 90gsm FSC-certified paper, inserted into DL or C5 window envelopes, and injected directly into Royal Mail International Priority Airmail with electronic customs pre-clearance.Delivery transit averages 3 to 5 business days across Western Europe and 5 to 7 business days worldwide, allowing your engineering team to manage global physical communications through a single unified API without maintaining foreign mailhouse relationships.

Modern serverless architecture: Edge functions, Next.js Server Actions, and idempotent background workers

Modern cloud architectures have largely abandoned heavyweight monolithic servers in favor of lightweight serverless functions, edge runtimes, and asynchronous event streams.LetterAPI was engineered specifically for this modern paradigm: our API surface requires zero heavyweight SDK binaries, native C++ extensions, or browser automation instances.You can invoke LetterAPI directly from Cloudflare Workers, Vercel Edge Middleware, Next.js Server Actions, AWS Lambda, or Supabase Database Functions using standard Web API `fetch()` primitives in under 5 milliseconds of cold-start overhead.When dispatching letters from distributed asynchronous workers (such as BullMQ, Inngest, Celery, or AWS SQS), network timeouts and consumer retries can potentially risk double-mailing recipients if not handled defensively.To completely prevent duplicate mailings, LetterAPI supports the standard `Idempotency-Key` HTTP header: pass your domain entity ID (such as `letter-invoice-9821-final-notice`) in the request headers.If a network glitch causes your worker to retry the dispatch call, LetterAPI recognizes the existing key, bypasses re-printing, and returns the existing letter record with HTTP status `200 OK` rather than generating a second postal charge.

The developer transformation: Unlocking the physical world from your terminal

For decades, the physical world has felt disconnected from the speed and elegance of modern software development.Developers who could ship a mobile app to millions of users in minutes were left feeling helpless when a business requirement demanded sending a real physical letter.LetterAPI permanently dismantles this barrier.By abstracting away the entire physical machinery of paper reels, printing presses, folding machines, and postal logistics behind a clean REST interface, we empower developers to treat physical letterboxes as an accessible cloud primitive.You eliminate the manual drudgery of postrooms and office franking machines.You protect your company with court-proof, trackable, and GDPR-compliant physical communications.And you deliver unforgettable, tactile customer experiences that bridge the digital screen and the physical kitchen table.The entire postal infrastructure of the United Kingdom is now just an API call away.

Ready to send your first physical letter?

Stop dreaming about automated correspondence and start building.Create your free LetterAPI developer sandbox account right now, copy your API key, and send your first physical letter from your terminal before your coffee gets cold.Welcome to the modern era of programmatic mail.