On this page
- How customer birthday cards work with a direct mail API
- When to mail customer birthday cards from an API
- Storing birthdays and other dates for API mail
- Idempotency-Key and a sent log: one birthday card per person by API
- Opt-outs, moves and bad addresses before the API batch
- Signup drips by API: a card on day 0, 14 and 30
- Code: a daily customer birthday card job with the Mailr API
- Customer birthday card questions from API senders
How customer birthday cards work with a direct mail API
A request to Mailr prints in the next print run. There’s no field for a send date, so the date logic is yours, and it fits in one job that runs every day:
- Pick who’s due. Everyone whose birthday is 14 to 21 days from today, who still wants mail and hasn’t had a card for this birthday.
- Log them first. One row per person and birthday, tagged with today’s run, so no later run can pick them again.
- Send one batch. Up to 1,000 people per request, each with their own name on the card, and an Idempotency-Key built from the day.
- Save what came back. The batch id and each piece id go on the log rows.
On December 1, that means the birthdays from December 15 to 22. A customer with a December 8 birthday was picked on November 17 and is already in the log. A customer who opted out is skipped.
| customer | birthday | days out | this run |
|---|---|---|---|
| Maya | Dec 8 | 7 | Sent Nov 17 |
| Leo | Dec 15 | 14 | Due |
| Priya | Dec 22 | 21 | Due |
| Sam | Dec 22 | 21 | Opted out |
| Ana | Jan 6 | 36 | Not yet |
The job can run anywhere that runs code on a timer: a crontab line, a Vercel schedule, EventBridge Scheduler on AWS, Cloud Scheduler on Google Cloud or a Cloudflare Cron Trigger. A CRM workflow can call Mailr once per contact instead, from a HubSpot custom code action or a Zapier step; each run sends one card. Key those requests on the person and the date, such as birthday-1042-2026-12-22, and write the card’s id back to the contact.
When to mail customer birthday cards from an API
Work back from the birthday. USPS says Marketing Mail takes 3 to 10 business days and doesn’t guarantee it; the USPS Marketing Mail post has the rules. Mailr puts each live card in the next print run in Phoenix and doesn’t promise a delivery date. Mailr’s advice for dated mail, like an event invite, is to send it about three weeks ahead.
So the job picks birthdays 21 days out. It also takes anyone 14 to 20 days out who hasn’t had a card, which covers days the job didn’t run and customers who signed up recently. Under 14 days, the slow end of the USPS range (10 business days is two calendar weeks) plus the wait for a print run can put the card after the birthday, so the job leaves those people for next year.
At the fast end, a card picked 21 days out lands well before the day. Write it for the birthday month, not the date: “Happy birthday month, Maya” reads right whenever it arrives, and an offer that runs through the month covers the early ones.
Storing birthdays and other dates for API mail
- Month and day only. Store the birthday as two numbers. You don’t need the year to mail a card, and not asking for it keeps one more piece of personal data out of your database.
- February 29. Three years out of four have no February 29, so pick a rule: the code below mails for February 28. The next leap year is 2028.
- Time zones. Work out “today” in your business’s time zone. Servers often run on UTC: a job at 9 pm in New York runs after midnight UTC, and a script reading the UTC date would build tomorrow’s key and pick tomorrow’s list. The customer’s own time zone doesn’t matter for a card mailed weeks ahead.
- Anniversaries and renewals. A signup anniversary uses the signup date’s month and day, with the number of years as a merge value. A renewal reminder uses the full renewal date. Both have to arrive before the date, so the same 14-to-21-day window works.
Idempotency-Key and a sent log: one birthday card per person by API
Two things stop a second card, and the job needs both:
- The Idempotency-Key. Each batch carries a key built from the day and the batch number, such as
birthday-2026-12-01-0. If the job runs again that day, Mailr returns the first batch instead of printing it again. Mailr keeps a key for 24 hours; the details are under safe retries in the docs. - The sent log. One unique row per person, kind and date (customer 1042, birthday, 2026-12-22) means the next day’s run can’t pick the same birthday, even though its key is different.
The order matters. The job writes the day’s rows to the log first, then sends exactly those rows in a fixed order, so a re-run the same day sends the same list under the same key. A replayed response can come back without its list of pieces, so the log always keeps the batch id and keeps the piece id when there is one. If a run still has no batch id the next day, its key has expired: check the Mailr dashboard for that day’s batch before sending again.
Opt-outs, moves and bad addresses before the API batch
- Opt-outs. Keep a do-not-mail flag on the customer and filter on it in the query. Set it whenever someone asks you to stop, whatever channel they ask on.
- Moves. People move without telling you. Run the customer table through NCOA at least every 95 days, update the new addresses, and set do-not-mail on people who moved without leaving one.
- Bad addresses. A batch is all or nothing, and with
"verify": trueone undeliverable address stops the whole day’s cards. Check each address when the customer saves it, withPOST /v1/addresses/verify, and store the corrected one. The CASS address verification post explains each result. - Long or missing names. A merge value longer than its field also fails the batch. A first name can be 14 characters, so the code trims it and fills a blank one; personalized direct mail covers fallbacks.
Signup drips by API: a card on day 0, 14 and 30
A drip counts forward from a date instead of back from one, so there’s no lead time to plan: the card only has to arrive after the date. The Node tab below sends a card on the day someone signs up, on day 14 and on day 30, from the same log table. Each step has its own kind in the log, so a person gets each card once, and each step catches people up to three days late if the job missed a day.
If the day 0 card should go out the moment someone signs up, send it from your signup handler instead, the way the Stripe direct mail guide sends a welcome letter when a subscription starts.
Code: a daily customer birthday card job with the Mailr API
# birthday_cards.py: run once a day (see the crontab tab). Env: MAILR_API_KEY. pip install requests
# app.db, or your own database with the same columns:
# customers(id, name, first_name, line1, line2, city, state, zip, birth_month, birth_day, do_not_mail)
# mail_log(customer_id, kind, occurs_on, run, batch_id, piece_id) with UNIQUE(customer_id, kind, occurs_on)
# do_not_mail = 1 for anyone who asked you to stop, or moved and left no new address (from NCOA).
import datetime, os, sqlite3
from zoneinfo import ZoneInfo
import requests
LEAD_MIN, LEAD_MAX = 14, 21 # mail birthdays 14 to 21 days away
today = datetime.datetime.now(ZoneInfo("America/New_York")).date() # your business's date, not the server's
run = f"birthday-{today.isoformat()}" # birthday-2026-12-01
db = sqlite3.connect("app.db")
db.row_factory = sqlite3.Row
def next_birthday(month, day):
for year in (today.year, today.year + 1):
try:
d = datetime.date(year, month, day)
except ValueError: # February 29 in a year without one: mail for February 28
d = datetime.date(year, 2, 28)
if d >= today:
return d
stuck = db.execute("SELECT DISTINCT run FROM mail_log WHERE kind = 'birthday' AND batch_id IS NULL AND run <> ?",
(run,)).fetchall()
if stuck: # an earlier day's batch may have gone through, and its key has expired: check the dashboard by hand
print("Not sent, or not recorded:", [r["run"] for r in stuck])
# 1. Freeze today's list once. A re-run today skips this and sends the same rows.
if not db.execute("SELECT 1 FROM mail_log WHERE run = ?", (run,)).fetchone():
for c in db.execute("SELECT id, birth_month, birth_day FROM customers WHERE do_not_mail = 0 AND birth_month IS NOT NULL"):
when = next_birthday(c["birth_month"], c["birth_day"])
if LEAD_MIN <= (when - today).days <= LEAD_MAX:
db.execute("INSERT OR IGNORE INTO mail_log (customer_id, kind, occurs_on, run) VALUES (?, 'birthday', ?, ?)",
(c["id"], when.isoformat(), run)) # IGNORE: already logged for this birthday
db.commit()
# 2. Send today's rows in a fixed order, 1,000 to a batch, and record what came back.
rows = db.execute("""SELECT l.rowid AS log_id, l.batch_id, l.occurs_on, c.name, c.first_name, c.line1, c.line2,
c.city, c.state, c.zip
FROM mail_log l JOIN customers c ON c.id = l.customer_id
WHERE l.run = ? ORDER BY l.customer_id""", (run,)).fetchall()
for n, start in enumerate(range(0, len(rows), 1000)):
chunk = rows[start:start + 1000]
if all(r["batch_id"] for r in chunk):
continue # sent and recorded by an earlier run today
resp = requests.post(
"https://api.mailr.dev/v1/batches", timeout=60,
headers={"Authorization": f"Bearer {os.environ['MAILR_API_KEY']}",
"Idempotency-Key": f"{run}-{n}"}, # birthday-2026-12-01-0: the same key returns the first batch
json={"kind": "postcard", "size": "4x6",
"front": open("mail/birthday/front.html").read(), "back": open("mail/birthday/back.html").read(),
"merge": {"promo_code": "BDAY15"}, # the same on every card
"recipients": [{"to": {"name": r["name"][:40], "line1": r["line1"], "line2": r["line2"] or None,
"city": r["city"], "state": r["state"], "zip": r["zip"]},
"merge": {"first_name": (r["first_name"] or "friend")[:14], # each person's own
"birthday_month": datetime.date.fromisoformat(r["occurs_on"]).strftime("%B")}}
for r in chunk],
"description": f"Birthday cards {today.isoformat()}"})
resp.raise_for_status() # a 422 names the row to fix; nothing in that batch was created or charged
batch = resp.json()
pieces = batch.get("pieces") or [{"id": None}] * len(chunk) # a replay can come back without the piece list
db.executemany("UPDATE mail_log SET batch_id = ?, piece_id = ? WHERE rowid = ?",
[(batch["id"], p["id"], r["log_id"]) for p, r in zip(pieces, chunk)])
db.commit()
print(run, n, batch["id"], batch["count"], batch["price"])mlr_test_ key and a few test customers whose birthdays fall in the window. Each batch is checked and priced, every card gets a proof, and the pieces move through every status in about eight minutes. Nothing prints or charges. Run it a second time and it sends nothing, since every row already has a batch.New to the API? Send mail programmatically walks through the first request, and the templates show the print rules a card design follows.
Customer birthday card questions from API senders
Can Mailr mail a postcard on a set date?
No. The API has no send date: a live piece goes into the next print run. To mail for a date, run a daily job in your own system that sends each person when their date is 14 to 21 days away.
How far ahead should birthday cards be mailed?
About three weeks. USPS gives Marketing Mail 3 to 10 business days and doesn't guarantee it, so a card mailed 21 days out has room, and one mailed under 14 days out can arrive after the birthday.
What happens to February 29 birthdays?
In the three years out of four without a February 29, mail for February 28 or March 1. The code in this post uses February 28.
How do I make sure nobody gets two birthday cards?
Log each person and birthday before sending, with one unique row per person and date, and send each batch with an Idempotency-Key built from the day, such as birthday-2026-12-01-0. A re-run within 24 hours gets the first batch back, and the log covers every day after that.
What does a birthday card cost?
A 4x6 postcard is $0.85 per card on pay as you go, printing and postage included, and $0.66 per card on the Agency plan ($149 a month). Test cards are free.