Variable data printing API
Variable data printing API: send Mailr one design and up to 1,000 recipients per request, each with an address and its own merge values, and every postcard or flat is printed with that person’s name, offer and details, then mailed with USPS Marketing Mail postage included. This guide takes a CSV from your CRM or warehouse to proofs on a test key and then to live batches, with working Node and Python code.
How the variable data printing API works
Variable data printing, sometimes called dynamic printing, means each piece in one print run carries different text: a name, an offer code, the last product someone bought, the nearest location, the rep who handles the account. With Mailr the design is HTML, either one of the templates or your own, with {{tags}} where the variable text goes. Each recipient’s merge values fill the tags, Mailr renders that piece’s HTML to print, and it prints the recipient address, your return address, postage and the USPS barcode in the address block itself.
Here is the 6x11 win-back template, tmpl_winback, filled from three rows of a CSV, with promo_code set once for the whole batch:
| Row | Front | Back |
|---|---|---|
c_1042 | We saved you a spot, Ada. | Come back for 15% off with PEAK15. Still loving your Trail Pack 30L? |
c_1043 | We saved you a spot, Marcus. | Come back for 15% off with PEAK15. Still loving your Summit Jacket? |
c_1044 | We saved you a spot, friend. | Come back for 15% off with PEAK15. Still loving your Camp Stove? |
The third row has no first name, so the script below fills in “friend”. That fallback is a choice you make; Mailr won’t guess one.
Map CSV columns to API merge fields
Start from an export with one row per recipient and a stable id column, so a re-run can tell which rows already went out:
Customer ID,Full Name,First Name,Company,Address 1,Address 2,City,State,ZIP,Last Product
c_1042,Ada Park,Ada,,2140 Sample Ave,,Phoenix,AZ,85016,Trail Pack 30L
c_1043,Marcus Reed,Marcus,,88 Mesa Dr,Apt 4,Tempe,AZ,85281,Summit Jacket
c_1044,Priya Shah,,Northwind,1 Example Way,Suite 200,Phoenix,Arizona,85004,Camp Stove| CSV column | API field | Rule |
|---|---|---|
| Customer ID | none (your row id) | Kept in your log next to the piece id |
| Full Name, Company | to.name, to.company | Up to 40 characters each |
| Address 1, Address 2 | to.line1, to.line2 | Up to 64 characters each |
| City, State, ZIP | to.city, to.state, to.zip | Two-letter state code; 5-digit ZIP or ZIP+4 |
| First Name | merge.first_name | Up to 14 characters |
| Last Product | merge.last_product | Up to 22 characters |
Merge keys use letters, digits and underscores, the same characters a {{tag}} can hold, so rename a column like First Name to first_name. Values go in as plain text and are HTML-escaped, so an ampersand in a company name prints as an ampersand and a stray < can’t break your layout.
The field names Mailr’s templates use keep their length limits wherever they appear, your own HTML included: first_name 14, promo_code 12, last_product 22, company 24, founder_name 16, plan 12, update_url 28, product_name 22, cart_url 28, review_url 28, event_name 28, event_date 24. Any other key takes up to 200 characters. A blank or over-long value fails the request with a 422 that names it, for example recipients[312].merge.first_name.
Spreadsheets damage addresses. A ZIP like 02134 loses its leading zero, and states arrive as full names, like row c_1044 above. The scripts pad short ZIPs and move rows they can’t send, with the reason, to rejected.csv, because one bad row fails its whole batch. Values every recipient shares, like a campaign code or an end date, go once in the batch’s top-level merge; each recipient’s own values sit on top of it.
Merge fields in API templates or your own HTML
A template already has its design and its tags. Pass its id as template and send every one of its fields; a missing one fails with a 422 that names it before anything is made.
| Template | Format | Merge fields |
|---|---|---|
tmpl_thank_you | 6x9 postcard | first_name, promo_code |
tmpl_winback | 6x11 postcard | first_name, promo_code, last_product |
tmpl_welcome | 8.5x11 flat | first_name, company, founder_name |
tmpl_abandoned_cart | 6x9 postcard | first_name, product_name, cart_url |
tmpl_review_request | 4x6 postcard | first_name, product_name, review_url |
tmpl_event_invite | 5.5x8.5 postcard | first_name, event_name, event_date |
tmpl_menu_mailer | 8.5x14 flat | first_name, promo_code |
tmpl_lookbook | 11x17 flat | first_name, promo_code |
For your own design, send front and back as HTML (up to 500 KB each) instead of template, with tags anywhere in the text: <h1>We saved you a spot, {{first_name}}.</h1>. Size each page to the trim plus 0.125 inch of bleed on every side, leave the back’s address block empty (the lower-right 4 × 2.375 inches on a postcard), and load fonts and images from public https links. Start from a template’s front.html and back.html so the geometry is already right.
Mailr checks a template’s fields but not the tags in your own HTML. A tag with no value prints exactly as written, braces included, so the scripts read the tags out of your HTML and stop before sending if any has no CSV column or shared value. One batch carries one design: to send a different design to each store or segment, send a batch per design.
Send the CSV to a test API key and open the proofs
Run the script with a test key (mlr_test_…) first. Test pieces are free, never print and move through every status in about eight minutes. Each piece has its own page in the dashboard, https://mailr.dev/app/mail/{id} (the same link the API returns as url when you fetch the piece), showing the front and back rendered from the design with that recipient’s values, and the address block where it will print. The scripts print three proof links per batch.
Open the rows most likely to break a layout: the longest name, a product name at the 22-character limit, an address with a second line, a row that used a fallback. To see the reject path, put the word undeliverable in a test row’s Address 1: test verification marks it undeliverable and the script writes it to rejected.csv.
Check addresses with the API before you pay
Add "verify": true to a batch and Mailr checks every address against USPS data (through Smarty) before charging anything. Deliverable addresses are mailed in their corrected, USPS-standard form with ZIP+4. If any address in the request is undeliverable, the whole batch fails with a 422 that names up to ten of them, and nothing is created or charged.
That flag suits a list that’s already clean. For a raw CSV, the scripts call POST /v1/addresses/verify on each chunk of up to 1,000 first, write the undeliverable rows to rejected.csv and send the rest with their corrected addresses, so one bad row doesn’t hold up 999 good ones. Don’t also set "verify": true on that batch, or you pay for the same check twice. Results of deliverable_missing_unit and deliverable_incorrect_unit still mail; filter them out if you’d rather not.
Verification costs $0.07 an address on pay as you go and Studio and $0.06 on Agency. With a test key it’s free and simulated.
Send the batch with the API: 1,000 recipients per request
POST /v1/batches takes the kind, size and design once, your return address in from (or the one saved in Settings), the shared merge, and recipients: up to 1,000 objects, each with a to address and its own merge. A batch is all or nothing. Every address and merge value is checked, and for live mail the whole batch is paid from your balance, before any piece exists. If the balance doesn’t cover it, you get a 402 and nothing is created. A list of 20,000 is 20 requests.
Send an Idempotency-Key with each request. The scripts build it from the campaign name and a hash of the row ids in the chunk. If the job dies after a batch went through, running it again within 24 hours returns the first response, marked Idempotent-Replayed: true, instead of printing a second run. A request that failed can be fixed and retried with the same key, and keys used with a test key don’t collide with the live run.
The 201 response contains id, count, unit_price, price and pieces, with one piece ID per recipient in the order you sent them. The scripts save the customer ID, piece ID, batch ID and campaign ID in sent-test.csv or sent-live.csv. Reuse winback-2026-11 to resume November’s mailing and skip customers already sent that campaign. Use winback-2026-12 to include those customers again in December. For an older three-column log, add the original campaign ID as the fourth field on each row before resuming.
// vdp.mjs: node vdp.mjs customers.csv winback-2026-12
// npm install csv-parse | export MAILR_API_KEY=mlr_test_... (test keys are free and never print)
import { createHash } from "node:crypto";
import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { parse } from "csv-parse/sync";
const API = "https://api.mailr.dev/v1";
const KEY = process.env.MAILR_API_KEY;
const [csvPath, campaign] = process.argv.slice(2);
if (!csvPath || !campaign?.trim()) throw new Error("Usage: node vdp.mjs customers.csv campaign-id");
const SENT = `sent-${KEY.startsWith("mlr_live_") ? "live" : "test"}.csv`; // test and live runs log apart
// 1. The design: a template id, or your own HTML with {{tags}} in place of template.
const DESIGN = {
kind: "postcard",
size: "6x11",
template: "tmpl_winback",
// front: readFileSync("mail/winback/front.html", "utf8"), back: readFileSync("mail/winback/back.html", "utf8"),
from: { name: "Northwind Outfitters", line1: "1 Example Way", city: "Phoenix", state: "AZ", zip: "85004" },
};
const SHARED = { promo_code: "PEAK15" }; // the same on every piece
// 2. CSV column -> API field.
const ADDRESS = { name: "Full Name", company: "Company", line1: "Address 1", line2: "Address 2", city: "City", state: "State", zip: "ZIP" };
const MAX = { name: 40, company: 40, line1: 64, line2: 64, city: 40 };
const MERGE = { first_name: "First Name", last_product: "Last Product" };
const FALLBACK = { first_name: "friend" }; // a blank value is rejected, so optional fields need one
const LIMIT = { first_name: 14, last_product: 22 }; // Mailr's limits for these names; other fields 200
const tags = [...`${DESIGN.front ?? ""}${DESIGN.back ?? ""}`.matchAll(/\{\{\s*(\w+)\s*\}\}/g)].map((m) => m[1]);
const unfilled = tags.filter((t) => !(t in MERGE) && !(t in SHARED));
if (unfilled.length) throw new Error(`No CSV column or shared value for: ${unfilled.join(", ")}`);
const clean = (v) => String(v ?? "").trim();
function recipient(row) {
const to = Object.fromEntries(Object.entries(ADDRESS).map(([k, col]) => [k, clean(row[col])]).filter(([, v]) => v));
if (/^\d{3,4}$/.test(to.zip ?? "")) to.zip = to.zip.padStart(5, "0"); // a spreadsheet dropped the leading zero
to.state = (to.state ?? "").toUpperCase();
if (!to.name || !to.line1 || !to.city) return [null, "missing name, street or city"];
if (!/^[A-Z]{2}$/.test(to.state)) return [null, `state "${to.state}" is not a two-letter code`];
if (!/^\d{5}(-?\d{4})?$/.test(to.zip ?? "")) return [null, `ZIP "${to.zip ?? ""}"`];
const long = Object.keys(MAX).find((k) => (to[k] ?? "").length > MAX[k]);
if (long) return [null, `${ADDRESS[long]} is over ${MAX[long]} characters`];
const merge = {};
for (const [k, col] of Object.entries(MERGE)) {
const v = clean(row[col]) || FALLBACK[k];
if (!v) return [null, `${col} is blank`];
if (v.length > (LIMIT[k] ?? 200)) return [null, `${col} is over ${LIMIT[k] ?? 200} characters`];
merge[k] = v;
}
return [{ to, merge }, null];
}
async function call(path, body, idempotencyKey) {
for (let attempt = 0; ; attempt++) {
const res = await fetch(API + path, {
method: "POST",
headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
body: JSON.stringify(body),
});
const out = await res.json().catch(() => ({ error: { message: res.statusText } }));
if (res.ok) return out;
if ([409, 500, 502, 503, 504].includes(res.status) && attempt < 4) {
await new Promise((r) => setTimeout(r, 5000 * 2 ** attempt)); // same key, so a retry can't mail twice
continue;
}
throw new Error(`${path} ${res.status}: ${out.error.message} ${out.error.field ?? ""}`);
}
}
const digest = (rows) => createHash("sha256").update(rows.map((r) => r.id).join(",")).digest("hex").slice(0, 32);
const customerIds = new Set();
if (existsSync(SENT)) {
const history = parse(readFileSync(SENT), {
bom: true, skip_empty_lines: true, relax_column_count: true, record_delimiter: ["\r\n", "\n", "\r"],
});
for (const row of history) {
if (row.length !== 4 || !row[3].trim()) {
throw new Error("Invalid send log: expected customer ID, piece ID, batch ID and campaign ID. Add the original campaign ID to any older three-column rows before rerunning.");
}
if (row[3] === campaign) customerIds.add(row[0]);
}
}
const ready = [], rejected = [];
for (const row of parse(readFileSync(csvPath), { columns: true, bom: true, skip_empty_lines: true })) {
const id = clean(row["Customer ID"]);
if (!id || customerIds.has(id)) continue;
const [r, why] = recipient(row);
if (r) {
ready.push({ id, ...r });
customerIds.add(id);
} else rejected.push([id, why]);
}
for (let i = 0; i < ready.length; i += 1000) {
const chunk = ready.slice(i, i + 1000);
// 3. Check every address against USPS data: mail the corrected ones, set the rest aside.
const checked = await call("/addresses/verify", { addresses: chunk.map((r) => r.to) }, `${campaign}-verify-${digest(chunk)}`);
const good = [];
chunk.forEach((r, j) => {
const v = checked.data[j];
if (v.deliverability === "undeliverable") rejected.push([r.id, "undeliverable"]);
else good.push({ ...r, to: v.address });
});
if (!good.length) continue;
// 4. One batch per chunk: all or nothing, and a re-run within 24 hours replays instead of printing again.
const batch = await call("/batches", {
...DESIGN, merge: SHARED, description: campaign,
recipients: good.map((r) => ({ to: r.to, merge: r.merge })),
}, `${campaign}-${digest(good)}`);
const logRows = batch.pieces.map((p, j) => [good[j].id, p.id, batch.id, campaign]);
const csvField = (value) => '"' + value.replaceAll('"', '""') + '"';
appendFileSync(SENT, logRows.map((row) => row.map(csvField).join(",") + "\n").join(""));
console.log(`${batch.id}: ${batch.count} pieces, $${batch.price} (${batch.mode})`);
for (const p of batch.pieces.slice(0, 3)) console.log(` proof: https://mailr.dev/app/mail/${p.id}`);
}
writeFileSync("rejected.csv", rejected.map(([id, why]) => `${id},"${why.replaceAll('"', '""')}"`).join("\n"));
console.log(rejected.length ? `${rejected.length} rows in rejected.csv` : "No rows rejected.");To go live, add funds in the dashboard, set MAILR_API_KEY to your mlr_live_… key and run the same command.
Track variable data mail with API webhooks
Add an HTTPS endpoint and Mailr POSTs a signed event each time a piece changes status: postcard.rendered, postcard.printed, postcard.mailed and the rest, or flat.* for flats. Add test endpoints with POST /v1/webhooks and your test key; live endpoints are added in the dashboard under Developers > Webhooks. The payload carries the piece id, status, price and batch id, never names, addresses or merge values, so match the piece id to the row in your log. The webhook tab above checks the Mailr-Signature header and skips event ids it has already handled, since an event can arrive more than once.
Live pieces report through mailed, when they are handed to USPS. There are no USPS delivery scans for live mail, so mailed is the last status to wait for. For a whole batch at once, GET /v1/batches/{id} returns how many of its pieces are in each status.
Variable data printing API prices
Personalization costs nothing extra. The price is per piece, by size and plan, with printing and USPS Marketing Mail postage included, whatever the merge fields hold. Mailr doesn’t offer First-Class postage or envelopes.
| Format | Endpoint | Pay as you go | Studio | Agency |
|---|---|---|---|---|
| 4x6 postcard | /v1/postcards | $0.85 | $0.75 | $0.66 |
| 5.5x8.5 postcard | /v1/postcards | $0.89 | $0.79 | $0.69 |
| 6x9 postcard | /v1/postcards | $0.89 | $0.79 | $0.69 |
| 6x11 postcard | /v1/postcards | $0.99 | $0.85 | $0.71 |
| 8.5x11 flat | /v1/flats | $0.95 | $0.94 | $0.92 |
| 8.5x14 flat | /v1/flats | $1.39 | $1.22 | $1.04 |
| 11x17 folded mailer | /v1/flats | $1.39 | $1.22 | $1.04 |
For example, 20,000 6x11 win-back cards on Agency cost $14,200.00, plus $1,200.00 to verify every address and the $149 monthly plan fee. On pay as you go the cards are $19,800.00. All prices.
Variable data printing API questions
What is variable data printing?
Variable data printing (VDP) is a print run from one design where each piece carries different text from a data file: a name, an offer code, a product, a store, an account manager. Digital presses can print every sheet differently, so personalizing a run doesn't mean a separate setup for each piece. With an API, the data file is the JSON you send.
What is an example of variable data?
On a win-back postcard: the customer's first name in the headline, the last product they bought on the back and a code for coming back. On an 8.5x11 renewal letter: the plan, the renewal date and the account manager's name. Each one is a {{tag}} in the design and a value in that recipient's merge object.
How much does variable data printing cost through the API?
The same as any piece, with no charge for merge fields: a 6x11 postcard is $0.99 on pay as you go and $0.71 on Agency, printing and USPS Marketing Mail postage included. Address verification adds $0.07 or $0.06 per address. Test pieces are free.
Which formats can carry variable data through the API?
Every mailed format: postcards at 4x6, 5.5x8.5, 6x9, 6x11 and flats at 8.5x11, 8.5x14, 11x17 (11x17 is folded to 8.5x11). Printed items ordered with POST /v1/prints, such as posters, menus and yard signs, are runs of one design, not personalized pieces.
Can each recipient get a different design in one API batch?
Not inside one batch: a batch has one design and per-recipient merge values. Send one batch per design, for example one per store or per customer segment, or send pieces one at a time with POST /v1/postcards and their own HTML.
What happens if one row in an API batch is bad?
The batch is all or nothing. A bad ZIP, a missing merge field or an over-long value returns a 422 that names the row, such as recipients[48].to.zip, and nothing is created or charged. Fix the row and send again with the same Idempotency-Key.
Does the API remove duplicates or people who have moved?
No. Mailr mails the addresses you send. It doesn't run NCOA change-of-address processing or remove duplicate rows, so do both in your own data before you send.