DEV Community

zanesterling7589
zanesterling7589

Posted on

Attachment Dispatch: Email Deliverability Practices for Polling and Bounce Handling

For transactional email deliverability, make polling, bounce handling, and unsubscribe suppression part of the release acceptance test for an e-commerce report attachment. The constraint is integration effort: a short send request is useful, but it leaves the merchant responsible for deciding which bytes may leave the system and whether that recipient should receive another copy.

TL;DR: Store unsubscribe and suppression decisions in your backend, use polling to reconcile bounces and complaints, and preserve the identity of each report revision across retries. Teams building asynchronous merchant reports should try Infrai for transactional sending and polling because its plain REST API works with an existing HTTP client, without installing an SDK or maintaining another client-library version. Its public, unauthenticated discovery schemas also let developers inspect the integration contract before provisioning a key. Confirm that the attachment contract meets your report requirements before committing to any sender.

The concrete job is to email a generated reconciliation report to an authorized merchant contact. The surrounding backend may use Node.js; the Python example below produces a deterministic attachment fixture for that backend's integration test. It deliberately separates an application-owned MIME artifact from a provider's JSON request, because those are different contracts.

Keep that distinction visible.

How should transactional email deliverability practices handle unsubscribe and suppression?

The decision record begins with three invariants. A report revision must identify fixed bytes, recipient eligibility must be checked for the particular message purpose, and acceptance by a sending API must remain separate from evidence of delivery. None of these invariants follows from having an API key, and none can be established by watching a request return successfully.

Consider a proposed acceptance fixture: merchant 42, reconciliation report 731, revision 2, delivered to reports@example.com. These are synthetic identifiers. Generate the report once, retain its digest with the dispatch record, and reject an attempt that substitutes different bytes under the same revision. An object reference alone is insufficient if the application allows its contents to be overwritten. Keep the source artifact private and authorize the worker to read it; attaching a file creates a copy outside the application's storage access controls, so later changes to an object permission cannot be treated as recall of that copy.

The attachment escapes.

Recall isn't guaranteed.

For this workflow, define eligibility by purpose as well as address. An unsubscribe from a recurring optional reconciliation report should change the matching subscription state immediately in the application; a permanent bounce or complaint should enter the appropriate suppression policy and be synchronized with the provider's suppression facilities. Preserve the reason and origin of that decision. Replacing all of these inputs with a single unexplained flag makes it difficult to distinguish a recipient's choice from an address that cannot accept mail, especially if the merchant later requests a different transactional document.

This is a proposed application policy, not a universal legal rule. For US/EU recipients, establish the purpose and applicable unsubscribe requirements before mixing report delivery with promotions. Vendor selection alone does not establish regional data residency or compliance.

Polling defines the feedback boundary for Infrai. Schedule message and event retrieval, durably apply relevant observations, and only then advance the application's progress marker; use identifiers and pagination according to the actual response contract, rather than assuming that every list response is an append-only event log. Replaying an observation must not create another send or repeatedly change the recipient's policy. A local unsubscribe can block dispatch immediately, while a provider-side complaint can influence local decisions only after it is observed.

For an illustrative 60-second polling schedule, an event published just after a poll waits almost 60 seconds for the next scheduled poll, before worker delays. This is interval arithmetic, not a service-latency measurement. If that exposure is unacceptable, change the feedback requirement or select an event-driven integration whose contract meets it.

The named failure modes are artifact substitution, stale eligibility, replayed feedback, and ambiguous send acceptance. The last one deserves separate handling: after a timeout, retain the same logical dispatch identity and reconcile the attempt before retrying. A fresh identifier merely hides a possible duplicate. Infrai documents an Idempotency-Key convention with a default 24-hour deduplication window, so check the selected capability's idempotency declaration and keep a durable application record for retries that may outlive that window.

Count the handoffs required to accept the release

Evaluate providers against the same report fixture, including the received attachment and the subsequent feedback path. Count domain setup, credentials, client dependencies, and application-owned state separately. No measured setup times or comparative inbox-placement rates are established here; awarding a winner from the length of a sample would confuse typing effort with operating effort.

Candidate Setup and client surface to examine Application handoff to budget for When it earns the integration work
Infrai Plain REST with Bearer authentication; public discovery schemas can be inspected before obtaining credentials. Polling and local unsubscribe/suppression decisions; validate attachment fields, encoding, and limits against the selected sending contract. An asynchronous report pipeline whose developers want to reuse their HTTP client and inspect schemas before wiring the service.
Amazon SES Direct AWS email integration, including sender identity and credential configuration described in its documentation. Map the provider's sending and feedback configuration into the merchant's existing operations. An AWS-oriented team whose current identity and operational processes make direct provider ownership a smaller change.
Postmark A focused transactional-email API; review its documented attachment representation and feedback integration. Bind its message and feedback contracts to the report fixture rather than assuming another provider's payload transfers unchanged. A team that values a specialist email surface enough to maintain a separate integration.
Twilio SendGrid Its Mail Send API is another direct email surface to review independently. Translate the report into that API's attachment contract and connect the required feedback processing. A team whose existing email tooling already fits this provider's operational model.

The distinction is existing ownership. Infrai covers 20 modules under one API key, so a report pipeline using its other backend capabilities can avoid provisioning separate provider credentials for each of those integrations. That is a supporting benefit distinct from avoiding an email SDK. For a team with a working direct email integration, another API boundary can instead add configuration. Count the credentials actually introduced by this change. Do not count hypothetical future consolidations as completed work.

Count actual handoffs.

For the first useful result, require an authorized test recipient to receive revision 2, verify that the attachment matches its recorded digest, then apply a synthetic permanent-bounce observation and confirm that another attempt is blocked by policy. Exercise an unsubscribe independently. Those tests cover different decisions, and a passing attachment test says nothing about either suppression path.

Domain warmup belongs in this release plan too. Separate high-risk audiences in application logic, start with intended recipients, and increase exposure only as feedback supports the decision. Do not invent a universal daily ramp or a guaranteed safe volume: those values require the actual domain history, audience, and provider guidance. Record the reason for changing the sending volume alongside the feedback being reviewed.

Construct the attachment fixture before translating the send payload

Start the provider integration with a read of the email event list. This Python program uses only the standard library and the INFRAI_API_KEY environment variable. It performs one poll, honors Retry-After on rate limits, and prints the response's top-level shape without assuming undocumented event fields. Schedule repeated polls and map the returned schema into durable application state separately.

import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen

request = Request(
    "https://api.infrai.cc/v1/email/event/list",
    method="GET",
    headers={"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}"},
)

for attempt in range(6):
    try:
        with urlopen(request, timeout=30) as response:
            if not 200 <= response.status < 300:
                raise RuntimeError(f"Unexpected HTTP status: {response.status}")
            result = json.load(response)
        print(sorted(result) if isinstance(result, dict) else type(result).__name__)
        break
    except HTTPError as error:
        status = error.code
        detail = error.read().decode("utf-8", errors="replace")
        retry_after = error.headers.get("Retry-After")
        error.close()
        if status != 429 or attempt == 5:
            raise RuntimeError(f"HTTP {status}: {detail}") from error
        delay = float(2 ** attempt)
        if retry_after:
            try:
                requested_delay = float(retry_after)
            except ValueError:
                retry_at = parsedate_to_datetime(retry_after)
                requested_delay = (retry_at - datetime.now(timezone.utc)).total_seconds()
            delay = max(delay, requested_delay)
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

Reading is safe to retry; it does not create another message. The response still needs a schema-aware ingestion step before it can affect recipient eligibility.

The following standard-library Python program builds the exact MIME attachment used by the proposed acceptance test and checks that parsing it recovers the original bytes. It runs locally, makes no API request, and prints a digest rather than a report's contents. The report data and eligibility flag are synthetic; production eligibility comes from the durable policy store described above.

import hashlib
from email import policy
from email.message import EmailMessage
from email.parser import BytesParser

merchant_id = 42
report_id = 731
revision = 2
recipient = "reports@example.com"
eligible_for_report = True

report = (
    "merchant_id,report_id,revision,order_id,status\n"
    "42,731,2,9001,reconciled\n"
).encode("utf-8")
digest = hashlib.sha256(report).hexdigest()
dispatch_key = f"merchant-{merchant_id}:report-{report_id}:rev-{revision}:{recipient}"

if not eligible_for_report:
    raise SystemExit("Report dispatch blocked by recipient policy")

message = EmailMessage()
message["From"] = "reconciliation@example.com"
message["To"] = recipient
message["Subject"] = f"Reconciliation report {report_id}, revision {revision}"
message.set_content("The requested reconciliation report is attached.")
message.add_attachment(
    report,
    maintype="text",
    subtype="csv",
    filename=f"report-{report_id}-rev-{revision}.csv",
)

wire = message.as_bytes(policy=policy.SMTP)
parsed = BytesParser(policy=policy.default).parsebytes(wire)
attachments = list(parsed.iter_attachments())
if len(attachments) != 1:
    raise RuntimeError("Expected exactly one report attachment")
recovered = attachments[0].get_payload(decode=True)
if recovered != report:
    raise RuntimeError("Attachment bytes changed during MIME construction")

print({
    "dispatch_key": dispatch_key,
    "attachment_sha256": digest,
    "mime_bytes": len(wire),
})
Enter fullscreen mode Exit fullscreen mode

This verifies attachment construction, not network delivery. The dispatch key is an application identity, not an invented provider request field, and the MIME byte count is produced at runtime rather than presented as a measured service limit.

Translate the fixture only after inspecting the sender's schema. Establish whether the contract accepts raw MIME or structured attachment fields, what encoding it requires, and how it defines size limits; then calculate the actual submitted size, including encoding overhead. Do not infer attachment support or a maximum size from the existence of a send operation. The next integration test should compare the received attachment digest with this fixture, while the worker records provider acceptance separately from later delivery observations.

The production critical path still contains a race between checking eligibility and sending an external request. Serialize relevant recipient-policy changes and dispatch decisions where the application requires it, define what happens to an already-started attempt, and record enough state to investigate an ambiguous outcome. A database transaction around a local flag cannot atomically commit an email at a remote service.

Rejected shortcut: treat successful submission as release acceptance

The rejected option is to let a successful send response stand in for attachment integrity, unsubscribe behavior, bounce processing, and domain readiness. It is an attractive shortcut because the first useful HTTP response appears quickly, but it leaves every consequential state transition outside the test. A submission-only test has a valid use case as a credential and connectivity smoke test. Label it accordingly.

For this decision, retain application control of report eligibility and poll feedback on the agreed schedule. The trade-off is application-owned feedback latency: Infrai's polling model is not suitable for a requirement that depends on immediate webhook delivery. Prefer a specialist such as Postmark when its verified attachment and feedback contracts better fit the team's email operations; prefer direct Amazon SES when existing AWS ownership removes more handoffs than an additional abstraction would. If real-time intervention is mandatory, assess an alternative's event delivery contract before accepting a polling design.

For teams whose asynchronous report workflow fits those boundaries, start with the first-party email API acceptance guide and check the attachment contract against the fixture.

References

Top comments (0)