DEV Community

PantaleonShaw8478
PantaleonShaw8478

Posted on

Compliance Email API Explained — Malformed JSON, Missing Variables, HTML Preview

Validate malformed JSON and missing template variables before calling an email API for event notifications, and retain separate acceptance and delivery evidence for every customer support compliance notice. A successful send request alone cannot establish what the recipient received.

TL;DR: reject malformed JSON, missing template variables, and invalid recipient fields before dispatch; preview the exact template revision; then reconcile the API response with delivery events. Keep the notice identity stable across retries. Those controls matter more to an audit than which email API accepted the request.

Consider a support case that requires a policy notice. The operational question is specific: can the team reconstruct the approved wording, intended recipient, dispatch attempts, and subsequent delivery evidence without treating a rendered HTML preview as proof of delivery? That question also gives a practical way to evaluate providers.

How should an email API handle malformed JSON and missing template variables?

Start with rejection evidence.

For event notification emails, malformed JSON, missing template variables, and invalid recipient fields are common integration failure sources. A 400 Bad Request is a signal to inspect the request and its response body. It doesn't, by itself, identify which validation layer rejected the request. Preserve the specific error rather than assigning every rejection to the template renderer.

Start the runbook at the application boundary. Record the notice identity, template revision, attempt timestamp, response status, and a correlation identifier when one is returned. Keep the actual request and response evidence under appropriate access and retention controls; alert logs should carry enough context for triage without copying recipient details or notice contents into every monitoring system. A hash is useful for comparing artifacts, but it cannot reconstruct a missing artifact, and an unprotected hash beside an editable record does not establish an immutable audit trail. Keep the approved artifact itself available to the people responsible for reconstructing the notice.

Stop blind retries.

A structurally invalid request needs correction before resubmission. A timeout needs a different investigation because the sender may not know whether acceptance occurred. Treat that state as uncertain, reconcile it, and preserve the same business notice identity. Otherwise, a queue retry can turn a single support obligation into duplicate notices with conflicting audit records.

For a Node.js sender, the same boundary checks belong before its email API call. The Go example below isolates that logic so the payload and template can be checked without sending a notice.

Preserve the evidence boundary when choosing a provider

Define an application contract around the notice: its identity, recipient, approved template revision, required variables, and evidence states. Put the provider adapter behind that contract. Changing the service behind an email capability should leave the support workflow's calling code stable; the adapter still needs verification against the chosen service's actual schema and event semantics.

Infrai offers a REST API with no SDK required, one key and one bill, and vendor switching without changing application code. That stable capability contract keeps a backend change out of the support workflow's caller. The single API key covers 295 routes across 20 modules, reducing credential handoffs between the notice sender and its supporting services. Public, self-describing discovery supplies request and response JSON Schema without requiring a key, so integration review can inspect the payload contract before production credentials are issued. Email events use polling; pair collection with immediate API response logging and alerting, and require a different event contract if the evidence deadline demands pushed notifications.

Choose the evidence deadline first.

Polling creates an explicit evidence collection step. Set a collection interval appropriate to the notice deadline, retain the last successful collection time, and alert when reconciliation falls behind. Acceptance and subsequent event observation must remain separate states. A quiet poll is not proof of delivery. The trade-off is a collector the team must operate in exchange for an application contract that can outlast the selected backend vendor.

Compare alternatives against the same evidence requirements:

Option Reason to evaluate it Deciding check for this support workflow
Amazon SES A direct email service is a candidate when the notice artifact needs to remain an email. Demonstrate how an accepted request is linked to subsequent delivery evidence and the approved notice revision.
SendGrid Another email provider belongs in the comparison when evaluating an email-only integration. Require a working demonstration of rejection handling, template validation, and evidence export; don't assume equivalence from the product category.
Twilio SMS An SMS alternative changes the notice artifact: character encoding and segmentation become part of the review. Check GSM-7 versus UCS-2 segmentation and obtain approval for the actual SMS wording before treating it as an alternate channel.

This is an acceptance test matrix, not a claim that every provider exposes identical controls. The SES reference establishes the email service context; Twilio's documentation supplies the segmentation distinction. SendGrid remains a candidate whose exact evidence contract must be demonstrated for the chosen integration. Don't score undocumented behavior as supported.

Email and SMS also make different demands on the approved content. A rich HTML notice cannot be assumed to preserve its meaning when shortened into text segments. Keep that change in the approval process. Switching channels merely because a request failed would bypass the very evidence boundary the workflow is supposed to preserve.

Validate the notice before it enters the send queue

Use two gates. First, validate the local input contract, including required fields and a single well-formed JSON object. Second, validate the provider payload against its actual schema and preview the approved template revision during development. Preview and template updates help catch rendering issues before production sends; they don't replace recipient checks or a delivery evidence collector.

The following runnable Go program implements the local gate and retrieves the batch-send discovery schema for inspection before adapter development. Its notice fields are application-owned example data, not a vendor request schema. It parses one synthetic support notice, rejects unknown fields and trailing JSON, checks recipient syntax, requires two template variables, renders with HTML escaping, and prints a digest for artifact comparison. Save it as main.go and run go run main.go. Set INFRAI_API_ORIGIN to the service's HTTPS origin without a path and INFRAI_API_KEY to your credential. The read-only schema request sends no email; discovery itself is public, although this example includes the application's environment-based authentication pattern.

package main

import (
    "bytes"
    "crypto/sha256"
    "encoding/json"
    "fmt"
    "html/template"
    "io"
    "log"
    "net/mail"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

type Notice struct {
    ID       string            `json:"notice_id"`
    Revision string            `json:"template_revision"`
    To       string            `json:"recipient"`
    Vars     map[string]string `json:"variables"`
}

func validateAndRender(raw string) (Notice, []byte, error) {
    var n Notice
    dec := json.NewDecoder(strings.NewReader(raw))
    dec.DisallowUnknownFields()
    if err := dec.Decode(&n); err != nil {
        return n, nil, fmt.Errorf("decode notice: %w", err)
    }
    var extra any
    if err := dec.Decode(&extra); err != io.EOF {
        return n, nil, fmt.Errorf("expected exactly one JSON value")
    }
    if strings.TrimSpace(n.ID) == "" ||
        strings.TrimSpace(n.Revision) == "" {
        return n, nil, fmt.Errorf("notice identity and revision required")
    }
    address, err := mail.ParseAddress(n.To)
    if err != nil || address.Address != n.To {
        return n, nil, fmt.Errorf("recipient must be a plain email address")
    }
    for _, key := range []string{"case_id", "policy_version"} {
        if strings.TrimSpace(n.Vars[key]) == "" {
            return n, nil, fmt.Errorf("missing template variable: %s", key)
        }
    }
    t, err := template.New("notice").
        Option("missingkey=error").
        Parse("<p>Case {{.case_id}}: policy {{.policy_version}} applies.</p>")
    if err != nil {
        return n, nil, fmt.Errorf("parse template: %w", err)
    }
    var out bytes.Buffer
    if err := t.Execute(&out, n.Vars); err != nil {
        return n, nil, fmt.Errorf("render template: %w", err)
    }
    return n, out.Bytes(), nil
}

func inspectSchema() error {
    origin := strings.TrimRight(os.Getenv("INFRAI_API_ORIGIN"), "/")
    u, err := url.Parse(origin)
    if err != nil || u.Scheme != "https" || u.Host == "" ||
        u.Path != "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
        return fmt.Errorf("INFRAI_API_ORIGIN must be an HTTPS origin")
    }
    key := os.Getenv("INFRAI_API_KEY")
    if key == "" {
        return fmt.Errorf("INFRAI_API_KEY required")
    }
    client := &http.Client{Timeout: 15 * time.Second,
        CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
            return http.ErrUseLastResponse
        }}
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequest(http.MethodGet,
            origin+"/v1/discovery/email.batch.send", nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                if seconds > 60 {
                    return fmt.Errorf("retry deferred: Retry-After=%s", retry)
                }
                if d := time.Duration(seconds) * time.Second; d > delay {
                    delay = d
                }
            } else if date, err := http.ParseTime(retry); err == nil {
                if d := time.Until(date); d > delay {
                    if d > time.Minute {
                        return fmt.Errorf("retry deferred until %s", retry)
                    }
                    delay = d
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("discovery status=%d body=%s", resp.StatusCode, body)
        }
        if !json.Valid(body) {
            return fmt.Errorf("discovery returned invalid JSON")
        }
        fmt.Printf("discovery_schema=%s\n", body)
        return nil
    }
    return fmt.Errorf("discovery retry budget exhausted")
}

func main() {
    const raw = `{
        "notice_id": "support-case-482-notice-1",
        "template_revision": "policy-notice-r3",
        "recipient": "recipient@example.com",
        "variables": {"case_id": "482", "policy_version": "3"}
    }`
    n, rendered, err := validateAndRender(raw)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("notice=%s revision=%s html_sha256=%x\n",
        n.ID, n.Revision, sha256.Sum256(rendered))
    fmt.Println(string(rendered))
    if err := inspectSchema(); err != nil {
        log.Fatal(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Passing this program establishes a narrow result: the sample satisfies the local contract, renders locally, and the discovery response is valid JSON. Retrieving the schema does not apply it to a send payload; the adapter must perform that validation. This doesn't establish mailbox existence, provider acceptance, legal sufficiency, or identical rendering in a remote template engine. The embedded template and revision label must be bound together in the release process; merely changing the label proves nothing. JSON decoding also has limits: this example does not reject duplicate object keys. If the input can cross a boundary where different parsers might interpret duplicate keys differently, add duplicate-key rejection to the input contract before adopting this gate.

The schema reader uses a 15-second timeout and at most 3 attempts. It backs off on HTTP 429, honors Retry-After, and defers retries beyond 60 seconds to the caller rather than holding a worker. These are example operational limits, not measured service latency. This request only reads a schema; an adapter that writes must additionally use the capability's documented idempotency mechanism and check its response contract.

That distinction is deliberate. Local checks give fast, reproducible rejection of bad input. Provider preview checks the next boundary. The delivery record comes later.

Verify the record, then roll back the producer

Before enabling the producer, remove policy_version from the sample and confirm rejection before dispatch. Repeat with a trailing comma, an invalid recipient, and a second JSON object after the first. Then restore the input and put an ampersand into the case value to inspect HTML escaping. These are synthetic checks, not reported production results. Preview the same approved wording in the provider template engine, retaining the template revision and input used for that preview.

Test reconciliation separately.

For the controlled send, join the immediate API response and subsequent delivery events to the same notice identity. Verify that the evidence collector's last successful poll is visible and that a failed collection raises an alert. Test the duplicate-delivery path by replaying the same business notice through a controlled test setup: the application should preserve the identity and use the selected capability's documented idempotency mechanism. A request attempt must never silently become a second business notice. Don't interpret a delivery event as proof that a person read or legally acknowledged the notice.

If verification fails, pause the application producer and stop new submissions. Roll back the template and its required-variable contract together to the last approved revision, then repeat validation and preview. Keep already accepted and uncertain attempts in the reconciliation ledger; changing a template cannot recall a message already sent. Resume only after the team can account for those attempts. This makes rollback an operational action with a visible boundary, rather than a resend that erases the original evidence.

References

Top comments (0)