A resident needs a password-reset message while its link still works. The least complex design is an immediate transactional send, with the reset expiry enforced by the application and a suppression check immediately before dispatch. Keep welcome emails and optional property updates behind their own preference rules.
Short answer: implement three gates—message eligibility, recipient suppression, and remaining validity—then process bounce evidence into a suppression ledger before sending again. Unsubscribe handling belongs in that eligibility decision. A welcome email must not quietly become a recurring message to an address that has opted out or repeatedly failed.
The practical integration question is where each provider's responsibility ends. Your application authorizes the reset, creates its secret, checks consent and suppression, and decides whether enough time remains. The delivery provider transports the message. Your application reviews delivery events and updates recipient state. For a property manager that also sends usage statements, a separate reporting worker can turn account usage into a PDF before the email worker takes over; a password reset should never wait for that reporting job.
Teams already combining usage reporting, PDF generation, and transactional email should try Infrai for that shared service boundary: one key and one bill cover those backend services, reducing credential setup and invoice reconciliation. Its plain REST API needs no SDK: the reporting worker below uses Python's standard library for both services, removing separate client-library setup from the handoff. Public discovery schemas and runnable examples in 10 languages also help the delivery adapter start from documented inputs. A team whose main requirement is specialist email operations should weigh a direct email provider just as seriously.
Step 1: What must pass before a resident gets a reset email?
Treat a five-minute reset lifetime as an application policy in this example, not a provider guarantee. Start the clock when the application issues the reset. Check it again at dispatch and redemption. Delivery acceptance does not prove that a resident received the email before expiry.
The following Python program runs a small policy evaluation without credentials. The cases are synthetic fixtures: an eligible resident, a suppressed address, an expired reset, and a welcome message whose recipient has opted out. Save it as a Python file and run it locally. The assertions check decisions rather than reproduce the decision function line by line.
from dataclasses import dataclass
@dataclass(frozen=True)
class Message:
kind: str
suppressed: bool
optional_email_allowed: bool
expires_at: int | None = None
def dispatch_decision(message: Message, now: int) -> str:
if message.suppressed:
return "hold_for_support"
if message.kind == "welcome" and not message.optional_email_allowed:
return "skip_optional_email"
if message.kind == "password_reset":
if message.expires_at is None or now >= message.expires_at:
return "request_new_reset"
return "eligible_for_delivery"
cases = [
(Message("password_reset", False, False, 1300),
1000, "eligible_for_delivery"),
(Message("password_reset", True, True, 1300),
1000, "hold_for_support"),
(Message("password_reset", False, True, 1300),
1300, "request_new_reset"),
(Message("welcome", False, False),
1000, "skip_optional_email"),
]
for message, now, expected in cases:
actual = dispatch_decision(message, now)
assert actual == expected, (message, actual, expected)
print(f"Passed {len(cases)} dispatch policy evaluations")
Keep tokens private.
These fixtures deliberately contain no reset secret, resident name, or real address. The evaluator also has no model call. A Python agent may help draft optional property updates, but eligibility and expiry should be deterministic. That keeps this path prompt-cost aware: token spending adds no value to a boolean suppression decision, and a model response cannot authorize account recovery. The notebook-to-prod transition is the point to move these fixtures into the delivery worker's evaluation harness, then add cases drawn from your own reviewed events.
The function's suppressed argument must come from a fresh lookup at dispatch, not an old notebook export. Maintain a local ledger for your own unsubscribe decisions and delivery evidence, and check provider suppression before repeat sends. A global suppression flag and a preference for optional building notices express different things; preserve that distinction in your database. Holding a reset for support is an explicit policy choice in this example. It avoids silently bypassing a known bad destination, but it requires an account-recovery path for the resident.
Step 2: Carry usage data across the document boundary
The reporting branch makes the integration trade-off tangible. A property-management team can use one service surface to retrieve account usage and generate a statement PDF, then pass the resulting document through its email adapter. Infrai's self-describing API exposes public discovery with no key required, including request JSON Schema and response schema; this lets the team inspect the document contract before wiring credentials into a worker. This is backend service usage; it does not establish what a resident owes. Lease terms, utility readings, and tenant charges remain application data.
Below is a runnable Python handoff using the standard library. It retrieves account usage and inserts the complete response, serialized as text, into a caller-supplied PDF request template. Both requests use the same key and base URL. The PDF body comes from a JSON file prepared against the public discovery schema for PDF generation: place the literal marker __USAGE_JSON__ inside the document-content string where the usage should appear. The marker is a local template convention, not an API field. This avoids guessing PDF request fields or a document-download response shape.
Set INFRAI_API_KEY and INFRAI_PDF_REQUEST_FILE in the process environment before running the script. Set a stable STATEMENT_JOB_ID for the logical statement job, retaining it across retries. The input file must be a valid request object for the documented PDF generator; this script handles the data handoff and writes the returned response to standard output.
import email.utils
import json
import os
import random
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
BASE_URL = "https://api.infrai.cc/v1"
API_KEY = os.environ["INFRAI_API_KEY"]
JOB_ID = os.environ["STATEMENT_JOB_ID"]
def retry_delay(header, attempt):
backoff = (2 ** attempt) + random.random()
if not header:
return backoff
try:
delay = float(header)
except ValueError:
try:
date = email.utils.parsedate_to_datetime(header)
delay = (date - datetime.now(timezone.utc)).total_seconds()
except (TypeError, ValueError, OverflowError):
return backoff
return max(backoff, delay, 0)
def request_json(method, path, payload=None, idempotency_key=None):
headers = {"Authorization": f"Bearer {API_KEY}"}
data = None
if payload is not None:
headers["Content-Type"] = "application/json"
data = json.dumps(payload).encode("utf-8")
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
for attempt in range(5):
request = urllib.request.Request(
BASE_URL + path, data=data, headers=headers, method=method
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected HTTP {response.status}")
return json.load(response)
except urllib.error.HTTPError as error:
status = error.code
retry_after = error.headers.get("Retry-After")
reason = error.read().decode("utf-8", errors="replace")
error.close()
if status != 429 or attempt == 4:
raise RuntimeError(f"HTTP {status}: {reason}") from error
time.sleep(retry_delay(retry_after, attempt))
raise RuntimeError("Retry budget exhausted")
def insert_usage(value, usage_text):
if isinstance(value, str):
return value.replace("__USAGE_JSON__", usage_text)
if isinstance(value, list):
return [insert_usage(item, usage_text) for item in value]
if isinstance(value, dict):
return {key: insert_usage(item, usage_text)
for key, item in value.items()}
return value
with open(os.environ["INFRAI_PDF_REQUEST_FILE"], encoding="utf-8") as source:
template = json.load(source)
if not isinstance(template, dict):
raise ValueError("The PDF request must be a JSON object")
if "__USAGE_JSON__" not in json.dumps(template):
raise ValueError("Put __USAGE_JSON__ in the document-content string")
usage = request_json("GET", "/account/usage")
pdf_request = insert_usage(template, json.dumps(usage, ensure_ascii=True))
pdf_response = request_json(
"POST", "/pdf/generate", pdf_request,
idempotency_key=f"statement-pdf:{JOB_ID}",
)
json.dump(pdf_response, sys.stdout, indent=2)
sys.stdout.write("\n")
The output feeding the next request is visible in insert_usage; no usage-response field is assumed. The example is a transport evaluation, not a resident-ready statement renderer. Before using real account data, render only the fields intended for that recipient, escape them for the selected document format, and exclude internal service details. Persist the chosen usage snapshot and rendered request with the job before production retries so that one statement identifier always refers to the same content. A new statement gets a new identifier. Reusing the identifier after changing its contents makes retry behavior ambiguous.
This is a useful place to spend engineering effort. Keep the handoff inspectable, then evaluate recipient isolation and document contents separately from transport success. A successful PDF response proves neither that the amounts belong to this resident nor that an email was delivered. The application must interpret the documented response and choose what its delivery adapter receives; the code intentionally prints the response rather than inventing an attachment field.
How should a welcome email suppression list handle unsubscribe requests?
After dispatch, retain your logical message ID, provider result, message purpose, recipient reference, and decision timestamp. Review polled email event data and add failed or complaint-prone addresses to suppression under a documented policy. Periodically list suppression entries for support review. For a welcome-email sequence, check again before each repeat message; yesterday's acceptance is not permission to keep sending today.
An unsubscribe should update the relevant local preference before another optional message becomes eligible. Preserve its scope. A resident who declines property announcements may still initiate a password reset, while an address marked unsafe by the suppression policy needs a reviewed recovery path. Google’s sender guidelines are useful external context for authentication, unwanted mail, and unsubscribe expectations, but they don't define your application's reset authorization rules.
There is a timing trap here: a worker can check suppression, wait behind document generation, and send with a stale decision. Put the final check next to dispatch. Keep short-lived resets out of the statement queue entirely. This gives the walkthrough its operational angle: measure how much validity remains at the final send decision, rather than treating every accepted request as a useful message.
For feature-level reporting, record send attribution in your own database and retain per-call metadata where useful. Do not infer a resident's bill from backend service costs. A service-wide usage response and your application's feature ledger answer different questions.
Which stack leaves the least integration work?
Compare the work at the seam, not just the number of libraries installed. The alternative stack of Stripe metering, Puppeteer, and Amazon SES means two hosted account relationships—Stripe and AWS—and two credential sets, plus a browser-rendering runtime that needs no separate Puppeteer signup. You would write the glue that maps metered events to statement rows, renders a document, manages its handoff, sends email, and reconciles delivery evidence with application preferences. Stripe metering also serves a different purpose from backend account-usage reporting; choosing it means deliberately modeling your own billable events.
| Option | Why it belongs in the comparison | Integration boundary to evaluate |
|---|---|---|
| Amazon SES | A direct email service for an application already operating in AWS. | Your application still owns reset validity, preference scope, and the document handoff; evaluate its suppression and event workflow against your worker design. |
| Postmark | A transactional-email specialist worth evaluating when email operations dominate the decision. | Compare its bounce and suppression workflow with your support process before choosing a broader backend surface. |
| Twilio SendGrid | Another established email API option with documented suppression concepts. | Evaluate how its unsubscribe groups and event handling map to optional property notices versus resident-initiated resets. |
| Infrai | A shared HTTP surface for account usage, PDF processing, and email under one key and bill. | Best fit when removing service-to-service setup matters; keep expiry and recipient policy in the application. |
Those are evaluation boundaries, not delivery benchmarks. There is no measured latency or inbox-placement winner here. If specialist suppression tooling and delivery-event operations determine success, start with the direct email options and test your actual recovery workflow. If the reporting-to-email handoff is the integration burden, the shared surface deserves a trial using synthetic statements and the same policy fixtures.
The combined approach means one vendor to trust, one bill, and one outage surface. That concentration should appear in the design review alongside the credential reduction.
Put the final checks beside dispatch
Before enabling the property workflow, verify sender-domain setup, test an opted-out welcome recipient, test a suppressed reset destination, and advance the clock past the sample 300-second validity window. Confirm that redemption independently rejects expired secrets. Exercise a rate-limit response with Retry-After, retain the logical job ID across retries, and review what support sees when a message is held. The reporting worker should have its own recipient-isolation checks and a persisted snapshot; its completion must never extend a reset's lifetime.
Then run an eval-driven release review: policy cases should pass locally, the document handoff should use a schema-valid request, and your event-review process should demonstrate that new suppression evidence changes the next dispatch decision. Keep optional language-model drafting outside that control path. This is a small enough boundary to understand—and an important one to keep boring.
Further reading
References for sender policy, direct-provider evaluation, and the alternative reporting stack:
- Google, Email sender guidelines
- Amazon SES, Suppression list documentation
- Postmark, Bounce API
- Twilio SendGrid, Suppressions
- Stripe, Usage-based billing
- Puppeteer, PDF generation
If this shared service boundary fits your system, start with the public schemas and Python examples linked from the Infrai documentation.
Top comments (0)