DEV Community

UlyssesDonovan1529
UlyssesDonovan1529

Posted on

Seller Notice — Email Deliverability Service Template Testing, Preview, and DKIM Ownership

Choose the email service around who owns the approved notice template. For a marketplace compliance notice, that decision determines how you connect a preview, the message submitted for delivery, and the record you can later explain. Domain authentication and suppression handling belong in the same decision, but they cannot repair an undocumented change to the notice itself.

TL;DR: Keep an approved template revision and its rendered evidence under application control, even when a provider hosts the template. Compare Amazon SES, SendGrid, and Postmark against that ownership boundary. A plain REST workflow is a good fit when template testing and preview, domain auth, DKIM rotation, suppression checks, and event retrieval cover your transactional notifications. Preserve delivery evidence separately from template approval.

Freeze the wording.

The scenario here is a marketplace notifying a seller about a compliance review. The example identifiers and wording below are fictional test fixtures, not legal guidance or production delivery results. The useful engineering question is whether the team can reproduce the notice that was approved without asking an agent to generate it again.

Which email deliverability service fits template testing and preview for seller notices?

There are two practical ownership choices: the application releases the template with its code, or a provider hosts a template that the application references. Either arrangement needs a named approval boundary. A mutable template identifier alone leaves an awkward question: which revision produced this seller's message? A local revision label and a digest of the rendered preview give the application a concrete reference to retain, although a digest alone does not establish who approved anything.

The proposed data flow is straightforward. A fictional seller record enters a deterministic renderer, the team reviews the resulting preview, and the application stores an approval record tied to those exact bytes. A separate delivery worker checks recipient eligibility and suppression status before submitting the approved notice. It then associates the provider's message identifier and subsequent delivery observations with that approval record. Domain verification and DKIM rotation are operational prerequisites around this flow, not fields that a content hash can prove.

That separation makes notebook-to-prod work much easier to reason about. The notebook can inspect the same fixture used by the release gate, while the sending worker remains responsible for actual delivery evidence.

Build a small preview gate before connecting the sender

This Python example runs with the standard library. It inspects the public template-creation discovery schema, then writes a local preview and audit fixture without sending email. Set INFRAI_BASE_URL to the trusted provider HTTPS API base ending in /v1 and INFRAI_API_KEY to your key. Discovery needs no key; the Bearer header demonstrates the credential convention used by authenticated operations. Run the script in a scratch directory. Every audit field is application-owned, rather than a provider request field.

import hashlib
import html
import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlsplit
from urllib.request import Request, urlopen

TEMPLATE_REVISION = "seller-review-notice-r3"
SUBJECT = "Action required: marketplace compliance review"
TEMPLATE = (
    "<p>Hello {seller_name},</p>"
    "<p>Please review case {case_id} in your seller dashboard.</p>"
)


def inspect_template_schema():
    base = os.environ["INFRAI_BASE_URL"].rstrip("/")
    parsed = urlsplit(base)
    if parsed.scheme != "https" or parsed.path != "/v1":
        raise ValueError("Use the trusted HTTPS API base ending in /v1")
    request = Request(
        base + "/discovery/email.template.create",
        headers={
            "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
            "Accept": "application/json",
        },
        method="GET",
    )
    for attempt in range(4):
        try:
            with urlopen(request, timeout=20) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected status: {response.status}")
                return json.load(response)
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            delay = float(2 ** attempt)
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    retry_time = parsedate_to_datetime(retry_after)
                    delay = max(
                        delay,
                        (retry_time - datetime.now(timezone.utc)).total_seconds(),
                    )
            time.sleep(delay)


def render_notice(seller_name, case_id):
    if not seller_name.strip() or not case_id.strip():
        raise ValueError("Seller name and case ID are required")
    return TEMPLATE.format(
        seller_name=html.escape(seller_name, quote=True),
        case_id=html.escape(case_id, quote=True),
    )


def content_digest(subject, body):
    payload = json.dumps(
        {"subject": subject, "html": body},
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def main():
    print(json.dumps(inspect_template_schema(), indent=2))
    body = render_notice("Cedar & Finch", "CASE-1042")
    if "Cedar &amp; Finch" not in body:
        raise RuntimeError("Preview gate rejected seller-name escaping")
    if "CASE-1042" not in body:
        raise RuntimeError("Preview gate rejected missing case reference")
    try:
        render_notice("Cedar & Finch", "")
    except ValueError:
        pass
    else:
        raise RuntimeError("Preview gate accepted an empty case ID")

    record = {
        "notice_id": "fixture-notice-1042",
        "template_revision": TEMPLATE_REVISION,
        "preview_digest": content_digest(SUBJECT, body),
        "created_at": datetime.now(timezone.utc).isoformat(),
        "approval_state": "awaiting_human_review",
        "delivery_state": "not_submitted",
    }
    Path("notice-preview.html").write_text(body, encoding="utf-8")
    Path("notice-audit.json").write_text(
        json.dumps(record, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps(record, indent=2))


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

The fixture exercises three checks: escaping a seller name, preserving the case reference, and rejecting an empty case identifier. It also leaves approval pending. Passing a content check must never silently approve a compliance notice.

The discovery request is read-only. It makes at most 4 attempts, honors Retry-After on HTTP 429, and otherwise uses exponential backoff. It creates no remote resource, so a write-idempotency key is unnecessary here. The response schema is printed for inspection; no undocumented template-create fields are guessed.

This is intentionally a narrow gate. It doesn't test mail-client rendering, authenticate a domain, query a suppression list, or prove delivery. Before submission, the worker should verify that its subject and rendered body still match the approved digest. If the provider performs the final rendering, retain that provider preview and its input variables too; a hash of locally generated HTML cannot establish that a different renderer emitted identical content.

Keep the preview.

A hash is useful for comparison, but it cannot reconstruct the message. The production design needs the approved artifact, its template revision, and the approval identity stored with appropriate access and retention controls. The local JSON file above is a teaching fixture, not a tamper-resistant audit system. Its Python formatting syntax also isn't Mustache: if the production template uses Mustache, test that renderer against the syntax manual rather than assuming the two formats are interchangeable.

This is a useful eval-driven boundary for an agent application. Let a model propose wording during drafting, then review and freeze it before delivery. Re-running a prompt on the send path introduces another output to approve and another token-consuming step. Deterministic substitution keeps the release check focused on approved content; it doesn't require the agent to rediscover the wording for every seller.

Compare services by the approval boundary

Amazon SES, SendGrid, and Postmark are real alternatives worth evaluating for transactional email. Their template documentation provides starting points for a hands-on comparison. The choice should turn on the workflow the marketplace can actually operate: who edits wording, who reviews a preview, and what the sender retains when a template changes. Avoid treating a product's template feature as evidence that your approval process is already solved.

Candidate Ownership decision Practical selection boundary
Amazon SES Evaluate its template workflow with the application team owning release and evidence collection. Favor it when that team wants to assemble the surrounding approval process; assign engineering time to that responsibility.
SendGrid Evaluate its transactional template workflow with the people who will edit and approve notices. Favor it when the editor-led process fits; test how an approved revision stays separate from subsequent edits.
Postmark Evaluate its template workflow around the marketplace's transactional notice fixtures. Favor it when the notice stream is the organizing unit; require the same retained-preview and evidence checks.

These are different selection boundaries, not comparative inbox-placement measurements. Run the same seller-name escaping fixture, missing-variable case, and approved-revision check against each candidate. The documentation links do not certify a particular marketplace's compliance obligations, and this comparison does not establish a deliverability winner.

Infrai combines a plain REST API with no SDK to install and a single key, single bill model spanning 295 routes across 20 modules, so adopting other backend capabilities through the platform can reduce separate credential setup and invoice reconciliation for the marketplace. Any HTTP-capable application can call it. Its public, self-describing discovery surface exposes request and response schemas without requiring a key, so the team can inspect the template contract before connecting the notebook prototype to a delivery worker. Template create, update, and preview sit alongside domain verification, DKIM rotation, suppression, and event-list capabilities. Events use polling, so the worker must retain its observation times and account for polling delay; this is an API-first fit for product notifications and receipts, with email OTP orchestration owned by the application and SMTP-based integrations outside its scope.

That combination supports a specific recommendation, not a universal one. Choose the API workflow when the team wants template control and deliverability basics together, and can operate the evidence collection itself. Choose an alternative when its template editing process fits the actual approvers better. A compact HTTP integration doesn't remove the need to decide who may change the notice.

A single key and unified billing reduce credential setup and invoice reconciliation across the adopted modules. This is operational consolidation, not evidence that template approval or delivery auditing is automatic. The trade-off is that event polling requires application-owned scheduling and evidence storage. This workflow is not suitable for a team that requires an SMTP relay; evaluate the SMTP integration offered by a dedicated transactional email service instead. Choose SendGrid, Postmark, or Amazon SES only after testing that integration against the same notice fixtures.

Treat authentication and delivery as separate evidence

A reviewed preview tells you something about content. Domain verification and DKIM rotation address sender authentication. Suppression checks govern whether a recipient should enter the send path. Event records describe subsequent observations. Combining these into one undifferentiated success flag would erase the distinction the audit needs.

For this proposed design, retain the application notice ID, approved revision, preview digest, provider message identifier, submission time, event time when available, and the time the application observed the event. Label those timestamps by meaning. A polled event recorded later should not silently become the original send time, and an accepted submission should not become a claim that the seller read the notice. Define the evidence threshold with the marketplace's compliance owner before calling a notice complete.

The specific trap is overwriting the approval artifact after changing a hosted template. The old message then points at today's wording, which makes a superficially tidy record difficult to explain. Preserve each approved revision and its rendered artifact independently of the current template editor state.

Authentication is necessary context, not a legal conclusion. The FTC's CAN-SPAM guide is a useful primary reference for assessing message purpose; this tutorial does not classify a particular notice or establish jurisdiction-specific compliance. Assess domestic delivery requirements separately rather than inferring compliance from the existence of an email API.

Close the loop before releasing a notice

Before release, name the template owner and record the approver. Retain the actual preview, its inputs, and the approved revision. Verify the sender domain, document the DKIM rotation procedure, and check recipient suppression immediately before sending. If an approved notice changes while waiting, keep it in an application-controlled queue until the new revision is approved; this keeps the release decision with the marketplace.

Then join submission and event records to the notice ID. Make write retries idempotent, treat polling delay as an explicit operational choice, and distinguish submission, delivery observations, and any separate acknowledgment. Keep the evidence store access-controlled and set retention with the responsible compliance team.

Finally, run the same fixtures from notebook to production. Add representative mail-client preview checks before trusting the rendered result. The operational goal is modest and valuable: the marketplace can explain what it approved, what it submitted, and what delivery evidence it actually collected.

References

Top comments (0)