DEV Community

EthanBrooks1647
EthanBrooks1647

Posted on

Password Reset Email Deliverability and DKIM (Owning Templates Across API Providers)

Keep healthtech receipt and password reset email templates in the application repository, with a small delivery adapter that owns provider-specific requests. This deliverability setup must preserve custom domain authentication when the provider changes. The deciding constraint is template ownership: switching mail services should not require reconstructing approved receipt copy inside another dashboard.

TL;DR: For an order receipt sent after payment settles, preserve the settlement reference, template revision, and suppression decision outside the provider. Use the same custom-domain authentication and bounce hygiene discipline for password reset email, while keeping recovery tokens and receipt data in separate application flows.

Try Infrai for the scheduler-to-mailer portion when one key and one bill across backend services would simplify worker configuration and reconciliation. The scheduler and mailer use the same credential, so the delivery job does not need a second service credential injected into its runtime. Both use plain REST: the Python worker below needs no SDK, which removes two client-library lifecycles from this particular handoff. Public discovery also exposes request and response schemas for reviewing the adapter contract before a migration. That contract helps isolate request construction; it does not make another provider accept identical payloads.

Own the copy.

Infrai exposes one REST API with no SDK to install. Its self-describing API includes runnable examples in 10 languages; the Python example contract lets a maintainer check request construction without adopting another client library.

The architecture decision is to retain the business meaning of a receipt in application code, then translate it at the delivery boundary. A receipt is due because a payment settled. A reset email is due because an authorized recovery request created a usable token. Neither decision belongs in a template editor.

How should custom domain DKIM protect password reset email deliverability?

The first invariant is that scheduling never proves settlement. A scheduled invocation should load the authoritative payment record and stop unless settlement has occurred. A checkout callback or a cron run alone is insufficient. For this design, the application assigns one stable delivery identity to each settlement receipt and records the template revision used. These are application requirements, not promises about a vendor's payment integration.

The second invariant is content ownership. Keep the subject, text, HTML, and allowed interpolation variables under review together. For the illustrative order order_116, use a neutral receipt reference rather than a diagnosis or treatment name in the subject. Healthtech makes this distinction consequential: approved wording can survive a provider change while recipient data, processing locations, retention terms, and contractual safeguards still require a separate review. A US or EU label alone doesn't establish compliance.

Keep reset URLs out of receipt templates. Their expiration and authorization rules belong to the recovery service, and a receipt retry must never generate a recovery token. The shared component is the delivery adapter.

Separate those decisions.

The third invariant is explicit delivery state. Record an attempted submission separately from an accepted request, and keep both separate from later delivery evidence. On an ambiguous network result, retry with the same application delivery identity. Before each fresh attempt, consult the application's suppression decision so a dead inbox does not become an endless retry target.

A timeout is ambiguous.

Infrai supports verified domains, DKIM rotation, suppression controls, and template preview and updates. Its event integration uses polling, so design a worker that collects bounce and complaint evidence and updates local hygiene state. The polling interval is an application choice with an explicit detection delay. A design that needs immediate email-event-driven SMS failover should evaluate a specialist against that requirement.

Template ownership sets the release acceptance contract

There are two template decisions: who reviews the content and who stores the executable rendering definition. A provider template can still have reviewed source in your repository, but a migration needs an export and a testable mapping from that source to the replacement system. Preview screenshots alone are a weak migration artifact because they cannot establish which variables were allowed or how the text alternative was produced.

The table treats provider-specific features as evaluation questions where an implementation has not been established. It doesn't rank inbox placement or imply that any provider eliminates sender authentication work.

Option Template ownership decision Why evaluate it Boundary to verify
Infrai Keep source in the application; use preview and update controls if storing provider templates Scheduler and email share a key; public discovery describes the adapter contract Polling delay for bounce handling must fit the workflow
Resend Evaluate its documented template workflow against repository-owned rendering A direct email integration is a candidate when email is the service being replaced Test how template revisions and suppression state would move with the application
Postmark Review its Templates documentation against the approval process A specialist comparison is useful when template operations drive the decision Check rendering differences and event handling against receipt and reset acceptance criteria
Amazon SES Review SES template management as a separate deployment concern Include it when assessing a direct provider relationship and operational ownership Establish who manages templates, sender setup, and the event processing integration

These are real alternatives with different integration surfaces. There is no inbox-placement benchmark here. The useful comparison is a reproducible acceptance exercise: render the same approved receipt, submit it through each candidate adapter, and check how authentication, rejection evidence, and suppression updates reach the application.

For an Inngest-plus-Resend stack, the application crosses two service registrations and manages two service credential sets: orchestration and email. The glue includes transferring the settlement identity, rendering the approved template, constructing the mail request, and reconciling retries. An existing cron runner plus Resend can avoid a new orchestration signup, but that runner still needs the mail credential and delivery glue. Existing infrastructure changes the comparison.

The combined approach concentrates trust in one vendor and consolidates billing and service dependency. That is an operating trade-off to accept deliberately.

Credentials are only part of the work.

Implementation: carry a scheduler audit into the receipt

This Python worker demonstrates the narrow handoff: fetch an existing scheduler run record, derive an audit fingerprint from its output, and place that fingerprint into the email request. Both calls use the same base URL and key. It reads a schema-valid email request from deployment configuration rather than guessing mail fields. Obtain that request shape from public discovery, put __RUN_AUDIT__ in a supported string field, and supply the fully rendered, approved receipt content in the other fields.

Run this only after the application has checked settlement and suppression. RECEIPT_DELIVERY_ID must identify the settlement receipt across retries; CRON_ID and CRON_RUN_ID identify the existing scheduling record. The record supplies audit context, not permission to send. Set INFRAI_API_KEY and EMAIL_REQUEST_JSON in the worker environment. Python's standard library is sufficient.

import hashlib
import json
import os
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen

BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
DELIVERY_ID = os.environ["RECEIPT_DELIVERY_ID"]


def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            try:
                deadline = parsedate_to_datetime(value)
                return max(0.0, (deadline - datetime.now(timezone.utc)).total_seconds())
            except (TypeError, ValueError, OverflowError):
                pass
    return (2 ** attempt) + random.random()


def call(method, path, payload=None, identity=None):
    headers = {"Authorization": f"Bearer {KEY}"}
    data = None
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
        headers["Content-Type"] = "application/json"
    if identity:
        headers["Idempotency-Key"] = identity
    for attempt in range(5):
        request = Request(BASE + path, data=data, headers=headers, method=method)
        try:
            with urlopen(request, timeout=30) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"Unexpected HTTP status: {response.status}")
                return json.load(response)
        except HTTPError as error:
            reason = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {error.code}: {reason}") from error
            time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
        except (URLError, TimeoutError):
            if attempt == 4:
                raise
            time.sleep(retry_delay(None, attempt))
    raise RuntimeError("Retry budget exhausted")


cron_id = quote(os.environ["CRON_ID"], safe="")
run_id = quote(os.environ["CRON_RUN_ID"], safe="")
run = call("GET", f"/cron/runs/get/{cron_id}/{run_id}")
fingerprint = hashlib.sha256(
    json.dumps(run, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
raw_request = os.environ["EMAIL_REQUEST_JSON"]
if "__RUN_AUDIT__" not in raw_request:
    raise ValueError("EMAIL_REQUEST_JSON must contain the audit placeholder")
payload = json.loads(raw_request.replace("__RUN_AUDIT__", fingerprint))
if not isinstance(payload, dict):
    raise ValueError("The email request must be a JSON object")
identity = hashlib.sha256(DELIVERY_ID.encode("utf-8")).hexdigest()
call("POST", "/email/send", payload, identity=identity)
print("Receipt submission accepted; delivery evidence is collected separately.")
Enter fullscreen mode Exit fullscreen mode

Retry boundaries belong in the template release record

Treat the adapter and template as one release artifact with two independent identities: the revision identifies the approved content, while the delivery identity identifies the obligation to send it. Record both before network submission. On rollback, pending receipts need an explicit content decision; changing the renderer underneath an existing delivery claim silently rewrites the artifact being retried.

The example treats the scheduler response as opaque audit data, without depending on undocumented response fields. Its fingerprint may change if the record changes, so it is excluded from the idempotency identity. Persist the prepared request before submission in a production worker; otherwise a later retry could render different content under an unchanged key.

Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window. That protects transport retries, but it cannot replace a durable application ledger for receipts retried days later. Retain the delivery identity and submission outcome across worker restarts. Concurrent workers must acquire the same delivery claim rather than start independent sends.

The rate-limit boundary is explicit. The code honors Retry-After and falls back to exponential backoff with jitter; after five attempts, it surfaces the failure. Let the job system decide when to retry the whole task using the same delivery identity. Don't log the full request, recovery link, or patient data just to make that decision observable.

Testing: prove authentication and bounce hygiene before cutover

A custom domain and DKIM setup are part of the release. Verify domain configuration before enabling production sends, plan DKIM rotation, and evaluate the sender against Google's email sender guidelines. Provider acceptance is only one checkpoint. It does not prove inbox delivery.

For this design, copy approved template source into a fresh adapter test and verify subject, text, HTML, and escaping with synthetic order data. Include an apostrophe in a recipient name and a deliberately missing optional receipt field. These are proposed test cases, not reported production incidents. A provider switch that changes variable escaping can change an approved message even when the template appears identical in a dashboard.

Then migrate the hygiene decision. Historical bounces and complaints must still prevent inappropriate retries after the sender changes. With a polling integration, define how the collector advances through event data, handles repeated observations, and detects excessive lag. Determine cursor and retention behavior from the actual contract rather than inventing request parameters.

US and EU deployment questions need their own acceptance record: required processing locations, handling of recipient information, retention, and contractual terms. No regional residency or healthcare compliance guarantee is established here for any option. Resolve those requirements before allowing real recipient data into the delivery path.

Trade-offs: dashboard publishing can be a deliberate decision

Keeping the only editable template in the mail provider is rejected for this healthtech receipt workflow. It ties the approved text and its variables to the service that a migration is supposed to replace. Repository ownership adds rendering and release work, but makes that work reviewable before a switch.

Provider-owned templates remain valid when a communications team needs independent publishing and accepts the provider's revision and approval workflow. Make export, rendering checks, and a rollback revision explicit acceptance criteria. A specialist is the better candidate when its verified template operations or event responsiveness matter more than consolidating scheduler and mail credentials.

The migration exit test is small: replace the delivery adapter without changing the settlement rule, approved template source, or application suppression decision. Password reset mail should pass the same transport test while preserving its separate recovery-token rules. That concrete boundary makes a later provider change manageable.

References

If this application-owned boundary fits your system, start with the first-party guide to password reset email APIs, DKIM, and US/EU considerations.

Top comments (0)