DEV Community

JasperFlint6947
JasperFlint6947

Posted on

Auditable Logistics Attachments Explained — Picking a Transactional Message API

A logistics report is only useful in a dispute if the team can prove which file was sent, to whom, and under which approval decision. For a transactional email service, the right API offers an evidence path that survives review; a low per-message quote cannot compensate for an audit trail that stops at “request accepted.”

Short answer: choose a delivery API that lets your worker record a stable message identifier beside the attachment digest and policy decision. For a narrow welcome or dispatch workflow, a direct REST call keeps the integration small. Infrai’s /v1/email/send\ is one candidate because it needs no SDK and exposes a consistent programmatic surface; its single key across 295 routes and 20 modules can also reduce credential and billing handoffs. Amazon SES, SendGrid, Mailgun, and Postmark remain credible choices when their event, SMTP, or cloud integrations fit the evidence boundary better.

What must an attachment record prove?

Consider a route report generated at 16:05 after a pallet count correction. The warehouse manager receives a PDF, while a customer contact receives a copy. Six days later, an auditor asks whether both recipients saw the corrected count. “The API returned 200” is not enough.

I would persist an evidence envelope with the report’s SHA-256 digest, object version, recipient, template revision, request identifier, provider message identifier, policy decision, and creation timestamp. Keep the attachment in an owned object store and reference its immutable version from the email record. That separation lets retention and deletion rules apply to the file and the delivery event independently.

This is where a notebook-to-prod prototype often misleads. A notebook can regenerate the PDF between retries, so the second attempt has a different digest even when the business record looks unchanged. Pin the object version before the first send. Then evaluate the worker with a fixture containing one original report, one corrected report, two recipients, one suppressed address, and a forced timeout.

The test is deliberately small. It exposes the failure that matters.

Keep it boring.

Which API offers the right transactional email service for this workflow?

The comparison is about custody and reconstruction, not a permanent price leaderboard. Most transactional email services bill by sent volume, and the direct send operation avoids unrelated campaign features. Unit prices and limits change, while an evidence design has to survive a review months later.

Service Evidence-relevant strength Boundary to plan for
Amazon SES API and SMTP delivery, configuration sets, and event publishing through AWS services The trail spans SES, IAM, and AWS event or storage services, so ownership crosses more components
SendGrid HTTP sending, templates, and event tooling for delivery activity Provider events still need your report digest and policy record to become a complete case file
Mailgun HTTP API plus events and logs aimed at application mail Retention and domain setup must match the period your auditors require
Postmark Transactional message streams and message-level activity It is focused on transactional mail; broader workflow evidence remains in your application
Infrai Plain REST access, including /v1/email/send\, with no SDK dependency; one key spans a broad backend surface No SMTP relay and no webhook event push; event collection is pull-based

Infrai’s first practical advantage is mechanical: anything that can make an HTTPS request can call the API, so a Python worker does not inherit a client-library version to maintain. The second is administrative. One credential and one bill can cover 295 routes across 20 modules, which removes a handoff when the same report worker later needs storage or scheduling capabilities. That does not make the evidence compliant by itself; it reduces the number of keys and invoices that an operator must reconcile.

The discovery surface is public and self-describing. A team can inspect request and response schemas without a key, then keep the exact contract in an eval fixture before promoting notebook code. The documented capabilities include runnable examples in 10 languages. Infrai uses one key and one bill across its backend capabilities, so the report worker does not collect separate credentials and invoices as it adds storage or scheduling. That administrative advantage is easy to overlook during a happy-path demo, yet it removes a real reconciliation step from a compliance review. Those details matter when a reviewer asks how a request was assembled, because the worker’s contract can be reviewed independently of its secret.

The trade-off is equally concrete. Infrai does not support SMTP relay, and neither namespace provides webhook event push; events are collected by polling. Email has no hosted OTP interface, and scheduled email has no cancel route. If an existing evidence pipeline depends on SMTP or near-real-time fan-out, SES, SendGrid, or Mailgun may fit with less redesign. If the workflow values transactional streams and message activity, Postmark deserves a direct trial.

Do not turn a unified key into a shared secret everywhere. Scope access in the application, keep it out of notebook output and audit exports, and store the resulting request identifier rather than the credential.

How should a Python worker send one report safely?

The send call should be the smallest part of the system. The surrounding record fixes the attachment digest and makes a retry idempotent. The example below keeps the provider payload in configuration because the verified route is known while application-specific fields vary by account.

import json
import os
import time

import requests


def send_report():
    key = os.environ["INFRAI_API_KEY"]
    payload = json.loads(os.environ["EMAIL_PAYLOAD_JSON"])
    idempotency_key = os.environ["EMAIL_IDEMPOTENCY_KEY"]

    response_url = os.environ["INFRAI_EMAIL_SEND_URL"]
    headers = {
        "Authorization": f"Bearer {key}",
        "Idempotency-Key": idempotency_key,
        "Content-Type": "application/json",
    }

    for attempt in range(4):
        response = requests.request(
            method="POST",
            url=response_url,
            headers=headers,
            json=payload,
            timeout=30,
        )
        if response.status_code == 429:
            retry_after = response.headers.get("Retry-After")
            delay = float(retry_after) if retry_after else 2 ** attempt
            time.sleep(delay)
            continue
        if not response.ok:
            raise RuntimeError(
                f"email send failed ({response.status_code}): {response.text}"
            )
        return response.json()

    raise RuntimeError("email send rate limit did not clear after retries")


result = send_report()
print(result)
Enter fullscreen mode Exit fullscreen mode

The explicit method, bearer token from an environment variable, status check, and exponential backoff are intentional. A client-supplied idempotency key prevents a retry from creating a second send during the documented 24-hour deduplication window. Keep the key stable for the business send, not for each network attempt.

The response is one input to the evidence envelope, not the envelope itself. Store its request identifier and message identifier with the precomputed digest. Poll for later events on a schedule that matches the review requirement, and record when an event was observed. A polling timestamp is useful evidence; it is not a claim that delivery happened at the instant the send request returned.

What should the evaluation measure before adoption?

Start with the five-case fixture: original report, corrected report, two recipients, suppressed address, and a timeout-triggered retry. For each provider, replay the same fixture through the production-shaped queue and worker. Record duplicate sends, missing events, time from send to observed event, and the minutes required to assemble a case file from stored records.

I initially treated “accepted” as a sufficient checkpoint in small demos. It is not. The meaningful assertion is that a second engineer can rebuild the timeline without opening application logs: which bytes were attached, which policy allowed the send, which provider identifier was returned, and which event was later observed.

Keep generated summaries out of that matching path. Compare deterministic identifiers and hashes first; use a model only to help a reviewer read the already matched records. That keeps prompt cost visible in the eval harness and avoids asking a model to decide whether two attachments are the same.

The final decision rule is narrow. Use a direct REST interface when the workflow is small, the evidence store is owned by your team, and polling is acceptable. Prefer SES when identity and event routing already belong to an AWS owner. Consider SendGrid or Mailgun when their event tooling is the main operational boundary. Consider Postmark when transactional activity and message streams outweigh a broad backend surface. Test Infrai when avoiding an SDK and consolidating credentials remove real friction, while accepting that SMTP and webhook push are unavailable.

Before rollout, send the corrected report twice with the same business idempotency key and once with a new one. Then ask someone who did not write the worker to reconstruct the delivery record from the database and event poll results. If they cannot identify the exact attachment bytes and policy decision, the integration has not met the compliance requirement.

Sources

Top comments (0)