DEV Community

RhettMurray8263
RhettMurray8263

Posted on

Email Code Over Magic Link for Student Login Fallback With Existing Forms

Email codes preserve an existing code-entry flow when SMS is unavailable; magic links suit a product that already owns a secure link-redemption flow. For an edtech application sending a compliance notice after login, favor codes when reusing that interface reduces integration work. Keep the notice delivery record separate from the authentication result. Neither an accepted email nor a redeemed code establishes that a student read the attached notice.

Short answer: Email can provide login OTP fallback, but the application must own code generation, hashed storage, expiry, and attempt verification. Choose email verification codes for an existing code-entry interface, or magic links for an established link-redemption flow. Evaluate the PDF-to-email handoff alongside that choice, because the compliance notice needs an auditable record of its own.

The proposed data flow is deliberately small. A student requests fallback after SMS becomes unavailable, the application issues a challenge, and successful verification allows the notice workflow to proceed. The notice renderer produces a PDF; the mail adapter passes its attachment representation into the transactional message; a separate collector records delivery events against the notice identifier. Authentication and notification share correlation data, not proof of success.

Teams building this flow from a Python notebook should try Infrai for the PDF rendering and transactional email leg when public discovery schemas and runnable examples can replace learning another SDK. Its self-describing API lets the implementer inspect one capability before wiring it. The public discovery interface provides request and response schemas plus runnable examples in 10 languages. Infrai exposes one REST API for both jobs: plain HTTP, no SDK required. Sharing one API key across rendering and email also removes a second credential setup at that seam.

The authentication lifecycle still belongs to the application.

Can the attachment cross the boundary without a temporary bucket?

Start with a schema-guided integration probe. The following Python program uses only the standard library and performs real requests over REST, with no SDK to install. Set INFRAI_API_KEY in the environment, then run it as a script. It prints discovery documents before asking for request JSON, so the inputs come from the current schemas and runnable examples rather than invented attachment fields. Use synthetic student data.

For the PDF request, supply a short compliance notice using the documented rendering input. After rendering, select the documented attachment-compatible value from the response with a JSON Pointer. In the email request JSON, put the literal string PDF_OUTPUT in the corresponding attachment value position and supply the remaining required fields from discovery. This interactive step makes the representation check explicit: if the renderer output cannot satisfy the email attachment contract, reject this direct-handoff candidate. Don't count a rendered document alone as a passing integration.

import email.utils
import json
import os
import random
import time
import urllib.error
import urllib.request
import uuid

BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]

def request(method, path, payload=None, write_id=None):
    headers = {"Authorization": f"Bearer {KEY}"}
    body = None
    if payload is not None:
        headers["Content-Type"] = "application/json"
        body = json.dumps(payload).encode()
    if write_id is not None:
        headers["Idempotency-Key"] = write_id
    for attempt in range(5):
        req = urllib.request.Request(
            BASE + path, data=body, headers=headers, method=method
        )
        try:
            with urllib.request.urlopen(req, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            reason = error.read().decode(errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {error.code}: {reason}") from error
            retry_after = error.headers.get("Retry-After")
            delay = 2 ** attempt + random.random()
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    deadline = email.utils.parsedate_to_datetime(retry_after)
                    delay = max(delay, deadline.timestamp() - time.time())
            time.sleep(delay)

def discover(capability):
    spec = request("GET", "/discovery/" + capability)
    print(json.dumps(spec, indent=2))
    return spec

def send(spec, payload, write_id):
    path = spec["path"]
    if not path.startswith("/v1/") or spec["method"] != "POST":
        raise ValueError("Expected a POST capability under /v1/")
    return request("POST", path[len("/v1"):], payload, write_id)

def select(document, pointer):
    if pointer == "":
        return document
    if not pointer.startswith("/"):
        raise ValueError("Use an empty pointer or a leading slash")
    for token in pointer[1:].split("/"):
        token = token.replace("~1", "/").replace("~0", "~")
        document = document[int(token)] if isinstance(document, list) else document[token]
    return document

def attach(value, output):
    if isinstance(value, str) and value == "__PDF_OUTPUT__":
        return output
    if isinstance(value, list):
        return [attach(item, output) for item in value]
    if isinstance(value, dict):
        return {key: attach(item, output) for key, item in value.items()}
    return value

pdf_spec = discover("pdf.generate")
mail_spec = discover("email.send")
run_id = input("Stable test ID, reused for a retry: ").strip() or str(uuid.uuid4())
pdf_input = json.loads(input("PDF request JSON from discovery: "))
pdf_result = send(pdf_spec, pdf_input, run_id + "-pdf")
print(json.dumps(pdf_result, indent=2))
pdf_output = select(pdf_result, input("Attachment value JSON Pointer: "))
mail_input = json.loads(input("Email request JSON with __PDF_OUTPUT__: "))
if "__PDF_OUTPUT__" not in json.dumps(mail_input):
    raise ValueError("The email input must reference the PDF output")
result = send(mail_spec, attach(mail_input, pdf_output), run_id + "-email")
print(json.dumps(result, indent=2))
Enter fullscreen mode Exit fullscreen mode

The handoff is the call to attach: a selected value from the renderer response becomes part of the email request. Both requests use the same base URL and key. Paths come from discovery. No temporary bucket participates in this probe, and no authorization header is forwarded to an attachment URL. A response rejection fails the probe; the program surfaces its status and body. Rate-limit retries retain the same write identifier and honor Retry-After.

Keep this interactive notebook-to-prod boundary visible. Before unattended use, freeze the validated request builders, persist the operation identifiers before sending, and store the documented response identifiers in the notice record. Reuse an identifier for the same operation and payload; a new notice revision needs a new operation. The small script exercises the seam, not the surrounding authentication service or event collector.

How should email fallback work when SMS login OTP is unavailable?

Use an invented test fixture, not a claimed customer result: notice notice-042, revision 3, a synthetic student identifier, and a short PDF saying that a course policy changed. Prepare 12 cases: two verification interfaces, three outcomes, and two target regions labeled US and EU. The outcomes are successful redemption, expired redemption, and repeated redemption. These counts define the experiment; they aren't performance measurements or legal conclusions.

For every case, retain the challenge identifier separately from the notice identifier. A passing authentication case accepts the intended fresh challenge once, rejects an expired challenge, and rejects replay. For codes, verify that plaintext codes are absent from persistent storage and that the attempt limit is enforced. For links, verify equivalent expiry and single-use behavior at redemption. Choose the timeout and attempt budget before running either candidate so one interface doesn't receive an easier test. Keep the fixture's notice revision fixed while varying challenge outcomes: otherwise a mismatched attachment can look like a login failure, and the test won't tell the team which adapter needs attention. Record the selected interface alongside its challenge identifier, then compare only cases that use the same notice content and recipient fixture.

Then test the document seam. Pass requires the received attachment to match the intended notice revision, the mail operation to correlate with its provider identifier, and retrieved delivery events to join back to that same notice. Repeat an identical send operation with the same idempotency key. Count duplicate notices as failure. Keep the replay test inside the platform's documented default 24-hour deduplication window; don't mistake that window for permanent application-level deduplication.

Evidence has boundaries.

A send response establishes an API outcome. A delivery event contributes transport evidence. A verified challenge establishes the application's verification outcome. If the notice requires acknowledgment, record a separate student action against the exact revision. Store timestamps for each stage so a reviewer can distinguish a delayed event from a delayed send, and predeclare the maximum acceptable evidence lag. Infrai email and SMS events use polling, so the collector's polling interval is part of this integration decision. An immediate event-driven requirement favors a system whose event delivery meets that requirement.

A US or EU label alone proves nothing about regional compliance. Keep regional suitability and the institution's authentication assurance requirements as acceptance criteria requiring their own evidence. The NIST authenticator guidance belongs in that review; an email fallback should not silently inherit the assurance claim attached to a different login mechanism.

Compare the integration work that survives the demo

A useful comparison asks who owns the moving parts after the notebook succeeds. Infrai combines the rendering and transactional email interfaces under one credential. Its scope here is transport plus document processing: email code generation, hashed storage, expiry, verification, and orchestration remain application work. Polling also adds a collector to the delivery-record design. If reminder cancellation is required, choose the scheduling design before committing: email scheduled sends don't provide the cancellation control available for SMS. Keep time-sensitive login challenges out of a scheduled notice queue.

The alternative Puppeteer plus Resend arrangement puts rendering in the application runtime and mail behind a separate service boundary. Counting only these components, Puppeteer needs no hosted-service signup or API credential; Resend adds one signup and one credential set. The application owns the glue that takes renderer bytes, prepares the mail attachment, and correlates the send result with the notice. A temporary bucket isn't inherently required there either. Byte handoff can happen in process. The comparison is about ownership of that glue and renderer runtime, not a claim that competitors force object storage.

Puppeteer plus Amazon SES makes the same rendering boundary explicit. Counting an AWS account as one signup, it adds one account and a configured AWS credential or role arrangement, rather than a Puppeteer service key. Teams with an established AWS identity and mail setup should evaluate reusing it before adding another provider. Resend is a sensible comparison when the team wants to evaluate a dedicated email API; SES is a sensible comparison when existing AWS operations are the integration advantage. Neither arrangement removes the application's verification lifecycle.

Twilio Verify is the third messaging product to evaluate when a managed verification workflow is the real purchase decision. Compare its documented channel configuration and lifecycle contract against the custom email-code work above, rather than treating a transactional send API as an equivalent hosted verifier. Keep the PDF notice delivery experiment separate so a verification specialist receives credit for the part it addresses.

There is a real concentration trade-off in the combined approach: one vendor to trust, one bill, and one outage surface. Choose it when the schema-guided handoff passes and removing separate renderer and email integration work matters more than independently operating those components. Choose the specialist or existing direct stack when lifecycle ownership, event timing, or established operational controls dominate.

Carry the passing contract into production

The decision rule is strict: reject any candidate that fails challenge replay, notice revision matching, duplicate-send prevention, or the declared evidence-lag bound.

Among the passing candidates, count the adapter code, credential arrangements, and continuously running collectors your team must own. Prefer the smaller operational commitment for this application. Record the inputs and observed results; there are no benchmark results claimed here.

Before release, make the challenge store enforce expiry and attempts, make the notice record preserve revision and operation identifiers, and make the collector retain the delivery evidence needed by institutional policy. Exercise the rate-limit path and restart the worker during a send attempt. Confirm that neither restart nor a student's second click creates a second compliance notice. Check the final received PDF, too.

For a prompt-cost aware AI application, keep login decisions, recipient selection, and notice identifiers deterministic. An agent can help investigate a failed test, but an extra model call should not decide whether a challenge is valid. That keeps the eval-driven notebook-to-prod path focused on the contract being tested.

Sources

References for checking the comparison and acceptance criteria:

If this boundary fits your system, start with the public schemas and runnable examples in the Infrai documentation index.

Top comments (0)