DEV Community

mT41Gzp73rc6
mT41Gzp73rc6

Posted on

Node.js Passwordless Welcome Email — 3 Retention Rules for Report Link Templates

Sending a generated fintech report with a passwordless welcome email starts with a transactional sender, an application-owned link to verify the address, and a record of which report was attached. The bill includes sending, report generation, attachment storage, and the work of investigating ambiguous delivery. Keeping another full copy of every rendered message adds a separate retention burden.

Consider an illustrative workload, not a vendor benchmark: 1,000 reports of 2 MB each produce 2,000 MB of attachment payload. Retaining three full copies produces 6,000 MB. In that storage model, attachment bytes dominate the retained payload; reducing three copies to one removes 4,000 MB without reducing the number of emails. That says nothing about which item dominates the actual invoice. Measure generation, sending, storage, and investigation separately before making that claim.

Short answer: for a Node.js passwordless welcome flow, generate and validate the verification or magic-link token in your backend, inject the link into a previewed transactional template, and send immediately. For the attached financial report, retain one authoritative artifact plus a small send ledger instead of archiving every rendered email. Select the sender by attachment handling, suppression behavior, and usable delivery evidence. A welcome email can carry a verification link; receiving the email does not itself verify the account.

The useful design question is how much evidence survives after the sensitive copies disappear.

What should survive when the report attachment is gone?

A report artifact, an authentication token, and a delivery record have different jobs. Giving them one retention clock creates trouble. A token should stop granting access after its validity window, while a delivery record may still be needed to investigate a complaint. Keeping the token inside an archived HTML body accidentally joins those lifetimes again.

Keep them separate.

For a concrete design example, a send ledger could associate report reference statement-0042 with a recipient account reference, template revision, artifact digest, application send intent, provider message identifier, and the latest observed delivery state. These are proposed application fields, not a provider request schema. Record the digest to identify the exact artifact; don't treat it as a replacement for the report when someone needs the original contents. Keep the recipient mapping access-controlled, because even a delivery ledger can expose financial relationships.

The first retention decision is to keep the authoritative report in the system that already governs financial records. The second is to retain enough send metadata to distinguish a missing attachment from a missing message. The third is to discard temporary renderings and token-bearing message bodies after their operational purpose ends, according to the institution's approved retention policy. There is no universal safe number of days for all three.

This changes the dominant term in the illustrative storage calculation: one governed report copy remains, while redundant message archives stop multiplying the same attachment bytes. The trade-off is concrete. A digest and template revision can identify what should have been sent, but cannot reproduce an expired token or prove how a particular mail client displayed the message.

How should a passwordless welcome email link verify the recipient?

The backend owns the signed verification token, its validation, expiration, and single-use handling. A mail sender transports the resulting link. Keep the purpose explicit: verifying an address and opening an authenticated session are different application actions, even if both start from an emailed link. Follow the OWASP guidance on secure token generation, expiration, and invalidation rather than treating possession of a provider message ID as authentication.

For the example account, the template could read: “Your account report is attached. Confirm your email address to finish setting up access.” The confirmation button receives a backend-generated link. The report reference belongs in the application ledger; a reusable secret does not. Preview the template before rollout to check branding, link substitution, and mobile rendering. Also inspect the final attachment filename and content in the chosen sender's supported attachment flow. A correct-looking HTML preview alone cannot establish that a PDF was attached.

There is a privacy decision before that send. Attaching a financial report gives the mailbox a durable copy, including copies retained or forwarded outside your application. If account verification is the boundary that authorizes release of the report, send the welcome verification first and release the attachment only after successful verification. If an established customer already has an authorized recipient address, the report delivery can follow that existing authorization. The welcome template must not quietly decide this policy.

A proposed implementation sequence is straightforward: generate the report, persist the send intent, mint the appropriate token, render the template, check suppression, submit through the transactional sender, and save the provider identifier. The actual send request must follow the selected provider's documented attachment schema. Don't guess the encoding, MIME fields, or size limit from another provider's example.

Compare senders at the attachment boundary

Evaluate Amazon SES, Postmark, and Twilio SendGrid against the same report fixture and the same suppression cases. Their documentation provides different starting points for implementation. Those differences help choose an integration surface; they do not establish a universal inbox-delivery ranking.

Option Relevant documented approach Decision for this workflow
Amazon SES Raw email sending provides a MIME-oriented integration path. Fits a team prepared to own MIME construction and inspect the full message; include that implementation responsibility in the choice.
Postmark Its email API documents attachments alongside transactional message fields. Fits a team seeking an explicit transactional message contract; validate report size and delivery evidence against the actual workload.
Twilio SendGrid Its Mail Send API documents personalizations, content, and attachments. Fits a team whose templates need that request structure; test the complete assembled message rather than just its template variables.

Infrai offers a self-describing API with public discovery and runnable examples, plus one API key and one bill across its backend services. That makes it another candidate for integrating the welcome-email portion: inspect the sending contract rather than learning a new SDK. The single-key, single-bill model can simplify credential and invoice handling for report generation and delivery. Validate attachment support for the selected sending contract before choosing it for report delivery, and design event collection around polling and token or email-code validation around application-owned logic.

Before translating the send request into Node.js, this Python standard-library probe checks the public discovery contract. Set INFRAI_DISCOVERY_URL to the email sending capability's public discovery URL from the provider documentation. The read needs no credential; if INFRAI_API_KEY is set, the probe uses Bearer authentication. It prints the contract for inspection rather than submitting a financial report and does not establish attachment support automatically. Only configure a trusted provider URL when supplying a credential.

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

url = os.environ["INFRAI_DISCOVERY_URL"]
if not url.startswith("https://"):
    raise ValueError("Discovery requires HTTPS")
headers = {"Accept": "application/json"}
api_key = os.environ.get("INFRAI_API_KEY")
if api_key:
    headers["Authorization"] = f"Bearer {api_key}"

for attempt in range(4):
    request = urllib.request.Request(
        url, headers=headers, method="GET"
    )
    try:
        with urllib.request.urlopen(request, timeout=20) as response:
            contract = json.load(response)
        if contract.get("method") != "POST":
            raise ValueError("Expected the transactional send contract")
        if contract.get("path") != "/v1/email/send":
            raise ValueError("Discovery returned a different capability")
        print(json.dumps(contract, indent=2))
        break
    except urllib.error.HTTPError as error:
        if error.code != 429 or attempt == 3:
            raise RuntimeError(
                f"Discovery HTTP {error.code}: "
                + error.read().decode("utf-8", errors="replace")
            ) from error
        delay = 2 ** attempt
        retry_after = error.headers.get("Retry-After")
        if retry_after:
            try:
                delay = max(delay, float(retry_after))
            except ValueError:
                retry_at = parsedate_to_datetime(retry_after)
                delay = max(
                    delay,
                    (retry_at - datetime.now(timezone.utc)).total_seconds(),
                )
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

The probe deliberately sends no customer data. Use the returned schema and runnable send example to settle the attachment fields before implementing the actual write, its idempotency handling, and the template binding.

That boundary matters. The evidence for sending a verification email is not enough to infer an attachment contract. Likewise, an attachment field in any competitor's documentation does not settle regional obligations, sender reputation, or the institution's rules for distributing customer reports. A dedicated email provider may be the clearer choice when the attachment workflow and its operational documentation carry more weight than a shared backend interface.

Use the same acceptance exercise for each candidate: a valid PDF, a suppressed address, an expired verification link, and an ambiguous submission result. Evaluate what the application can establish afterward. Price is secondary to whether the record answers the customer's actual complaint.

Retry the intent, and preserve uncertainty

Suppose submission times out after the sender may have accepted the message. Blindly resending can deliver two reports, each with a different verification link. A stable application send intent should bind the account, report version, and message purpose before the network request. Use the selected provider's documented idempotency mechanism where supported, with its documented scope and retention window. Local deduplication alone cannot establish what a remote service accepted during a timeout.

An unknown result should stay unknown until reconciled. Don't label it delivered to simplify the dashboard.

Check suppression before future transactional retries when a recipient has unsubscribed or hard-bounced. A newly generated report does not make that address healthy again. Treat a rate limit as a reason to back off, honor retry guidance, and retry the same logical intent. If the welcome link expires while delivery is delayed, the application needs an explicit recovery path; extending a token's validity silently is a poor substitute for one.

Delivery reliability also depends on the sender domain and mailbox requirements. Yahoo's sender guidance is a useful primary reference for authentication and sending practices. Provider acceptance, a delivery event, inbox placement, and successful link redemption answer different questions. Preserve those distinctions in the ledger. For this workflow, the final business outcome is an authorized customer receiving the intended report, not merely an API accepting a payload.

The deliberate deletion is temporary attachment copies, token-bearing bodies, and raw diagnostic payloads that no longer serve an approved purpose. Keep the governed report and sufficient access-controlled evidence to reconcile its send intent. When something goes wrong later, this choice costs you exact reconstruction of the original rendered message and its expired link. That is a defensible trade only if support can still identify the report, inspect the recorded delivery state, and issue a newly authorized send without reviving an old credential.

Further reading

References:

Top comments (0)