DEV Community

NielsChristensen4981
NielsChristensen4981

Posted on

Go Seller Notifications: Connecting Transactional Email and SMTP 2FA Login Boundaries

Use a transactional email API for email-based 2FA fallback when the application can own code generation and verification; retain an SMTP transport when the auth library only accepts relay credentials.

TL;DR: Changing the mail transport doesn't replace the login flow. For a gaming marketplace that emails a seller about a new order, the practical migration unit is the account lookup, the security challenge, and the notification worker together. Keep the seller's order alert independent of the challenge so a delayed alert cannot become an authentication decision.

Can a transactional email API replace SMTP relay for 2FA codes?

An SMTP configuration screen is a useful early warning. If the existing auth library asks for a host, port, username, and password, an HTTP email API cannot fill those boxes: someone must implement a transport adapter or change the integration. That work belongs in the estimate before selecting a provider.

Count the handoffs.

For an illustrative marketplace order, call it game-order-183, the seller account identifies the recipient, a login challenge proves access under the application's policy, and a separate message announces the new order. Those are three responsibilities even when one service supplies several capabilities. A mail send response should not advance the challenge to verified; only the application's verification operation should do that.

A release gate can make that distinction concrete without inventing a vendor uptime promise: define one SLO for eligible seller alerts accepted within the team's chosen deadline and another for completed login challenges, then track mailbox delivery separately wherever evidence permits. Set the actual deadlines from the game's operational requirements. An accepted request is insufficient evidence that the seller received or read the message, and a growing backlog can consume an OTP's useful lifetime before the worker reaches it.

Capacity planning starts with two arrival streams, security messages and order alerts. Estimate each stream's peak arrival rate, multiply by its retry allowance, and compare that demand with the throughput the team has actually validated. Reserve room for login traffic. A marketplace launch is a poor time to discover that a shared queue lets a flood of order notifications delay the security fallback.

Buy the transport, budget the integration

The comparison below is an implementation checklist rather than a feature scorecard. It deliberately asks what the team must connect and own; these are different purchasing decisions, and a managed identity product should not be evaluated as though it were merely a mail socket.

Option Role in this seller workflow Work to budget or confirm
Clerk Managed identity component in the alternative stack Map its account identity into the order worker; check the required login policy against its documentation.
Resend Email component in that stack Connect the order and challenge messages to its email interface; verify the transport your existing auth library can use.
Twilio SMS component for the fallback Connect the SMS decision to the same account and challenge state; review message segmentation when designing SMS content.
Amazon SES Another email delivery option to evaluate Compare its integration requirements with the existing email adapter; it doesn't remove the account-to-recipient mapping from the application.
Existing SMTP transport Preserve the interface an SMTP-only auth library expects Keep responsibility for account mapping, message intent, and application-owned verification explicit.
Application-owned email API adapter Buy delivery while retaining the challenge policy Implement the adapter, retry control, recipient selection, and verification lifecycle.

Infrai fits the API-adapter option with a self-describing REST API, one key, and one bill across account access, email, and SMS. Its public discovery requires no key and supplies request and response schemas plus runnable examples, so wiring a new capability starts with reading its contract rather than learning a new SDK. That shared credential also connects the account, welcome email, and SMS fallback without three credential integrations. The trade-off is explicit: it does not support SMTP relay or hosted email OTP, so an SMTP-only application needs custom integration and the application must generate and verify email codes. Email and SMS events require polling, which limits notification freshness; the combined workflow also has one vendor to trust and one outage surface. Keep immediate security messages out of scheduled delivery, enforce SMS geographic and spending controls in application policy, and establish regional compliance independently.

That last row still contains engineering.

The Clerk + Resend + Twilio alternative requires three service signups and three sets of credentials. Its glue maps the identity account to email and phone recipients, carries challenge state between components, and reconciles each service's suppression decisions before attempting fallback. A shared key reduces credential plumbing; it doesn't establish a shared definition of consent or make a suppressed email address a reason to contact a different channel.

Choose the combined approach when reducing that plumbing is worth the dependency concentration and the application already owns its login policy. Prefer the existing SMTP integration when replacing a transport hook would dominate the project, and evaluate managed identity when the work you want to buy includes authentication behavior. No price comparison resolves that distinction.

Carry the account result into a controlled send

Verify the sending domain before using it for security messages. DMARC is relevant to domain trust, but a DNS configuration isn't a guarantee that every mailbox will accept every message. Make domain verification a release prerequisite rather than a task left for the first production login.

The following Go program demonstrates the narrow handoff: read an account, select a recipient from its response, and use that value in an email request through the same client, key, and base URL. It is intended for a controlled test of the seller's order alert. It doesn't generate an OTP or authenticate a seller.

The exact account response shape and email request fields must come from the selected capability schemas. Instead of guessing them, this executable takes the verified email request as EMAIL_REQUEST_JSON and replaces one local marker, ACCOUNT_RECIPIENT, with a string selected from the account response by ACCOUNT_RECIPIENT_POINTER. The pointer uses JSON Pointer syntax; the marker is a local template convention, never a claimed API field. Put it only in the recipient value prescribed by the send schema.

Set API_BASE_URL to the service's v1 HTTPS base, INFRAI_API_KEY to the secret in the environment, ACCOUNT_ID to the test seller, and EVENT_KEY to a stable identifier for this order notification. Keep that identifier unchanged across retries. Supply the account pointer and request JSON from the capability contracts, then run the file with Go. No SDK is required.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func required(name string) string {
    value := os.Getenv(name)
    if value == "" {
        panic("missing environment variable: " + name)
    }
    return value
}

func request(client *http.Client, method, address, key, event string, body []byte) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(method, address, bytes.NewReader(body))
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        if body != nil {
            req.Header.Set("Content-Type", "application/json")
        }
        if event != "" {
            req.Header.Set("Idempotency-Key", event)
        }
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        data, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                wait := time.Duration(seconds) * time.Second
                if wait > delay {
                    delay = wait
                }
            } else if at, err := http.ParseTime(retry); err == nil {
                if wait := time.Until(at); wait > delay {
                    delay = wait
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, data)
        }
        return data, nil
    }
    return nil, fmt.Errorf("retry budget exhausted")
}

func recipientAt(raw []byte, pointer string) (string, error) {
    var value any
    if err := json.Unmarshal(raw, &value); err != nil {
        return "", err
    }
    if !strings.HasPrefix(pointer, "/") {
        return "", fmt.Errorf("recipient pointer must begin with /")
    }
    for _, token := range strings.Split(pointer[1:], "/") {
        token = strings.ReplaceAll(strings.ReplaceAll(token, "~1", "/"), "~0", "~")
        object, ok := value.(map[string]any)
        if !ok {
            return "", fmt.Errorf("recipient pointer must traverse JSON objects")
        }
        value, ok = object[token]
        if !ok {
            return "", fmt.Errorf("recipient pointer does not resolve")
        }
    }
    recipient, ok := value.(string)
    if !ok || recipient == "" {
        return "", fmt.Errorf("recipient must be a nonempty string")
    }
    return recipient, nil
}

func run() error {
    base := strings.TrimRight(required("API_BASE_URL"), "/")
    parsed, err := url.Parse(base)
    if err != nil || parsed.Scheme != "https" || parsed.Host == "" ||
        parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" ||
        parsed.Path != "/v1" {
        return fmt.Errorf("API_BASE_URL must be an HTTPS v1 base URL")
    }
    origin := strings.TrimSuffix(base, "/v1")
    client := &http.Client{
        Timeout: 15 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    key := required("INFRAI_API_KEY")
    account, err := request(client, http.MethodGet,
        strings.Replace(origin+"/v1/auth/user/get/{user_id}",
            "{user_id}", url.PathEscape(required("ACCOUNT_ID")), 1), key, "", nil)
    if err != nil {
        return err
    }
    recipient, err := recipientAt(account, required("ACCOUNT_RECIPIENT_POINTER"))
    if err != nil {
        return err
    }
    template := required("EMAIL_REQUEST_JSON")
    if !json.Valid([]byte(template)) ||
        strings.Count(template, "\"ACCOUNT_RECIPIENT\"") != 1 {
        return fmt.Errorf("request must be JSON with exactly one quoted recipient marker")
    }
    encoded, err := json.Marshal(recipient)
    if err != nil {
        return err
    }
    payload := strings.Replace(template, "\"ACCOUNT_RECIPIENT\"", string(encoded), 1)
    _, err = request(client, http.MethodPost, origin+"/v1/email/send",
        key, required("EVENT_KEY"), []byte(payload))
    if err != nil {
        return err
    }
    fmt.Println("Email API accepted the request; delivery requires separate evidence.")
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The response body remains internal; printing an account record into a worker log would create another copy of seller data. Non-success responses surface as errors, redirects are refused, and rate-limit retries honor a longer Retry-After value. Restrict those error logs as well: a provider error body can contain request details.

The retry budget is 4 attempts, with a per-request timeout of 15 seconds; these are example client settings, not provider guarantees or an SLO. Retry-After can extend the total runtime. Run this check in a bounded test worker; give a production worker a deadline derived from the message's remaining useful lifetime, plus jitter and a durable retry budget. A transport timeout is an ambiguous result, so any later retry must reuse the same event key and payload.

Do not copy this order-alert template into a security challenge without adding the challenge lifecycle.

Verify the seam before shifting traffic

Use a test seller with a verified sending domain and a mailbox the team controls. Check that the selected account response produces the intended recipient, that a missing recipient prevents the send, and that replaying the same logical order notification retains its event key. Observe delivery separately from acceptance. With pull-based events, choose a polling interval whose detection delay fits the alert objective rather than treating the send response as an event subscription.

For the security fallback, verify code expiry, attempt limits, single-use consumption, and the binding between challenge and account in application logic. Test a delayed notification after challenge expiry. It must never revive the challenge.

Then test the policy decision at the channel seam: an email suppression must not silently grant permission for SMS. Compare each channel's recipient eligibility before sending, and retain enough internal correlation to explain why game-order-183 produced an email, an SMS, or neither. Keep order identifiers out of secrets and keep challenge values out of logs.

Release gradually.

Rollback should switch the application adapter back to the previously validated transport while preserving challenge state, correlation records, and event identifiers. Pause the affected worker before switching so two transports don't race to send the same notification. A rollback cannot unsend mail; drain or reconcile ambiguous attempts before resuming, and never regenerate a fresh challenge merely because the delivery adapter changed.

The release decision is integration effort with evidence: a team comfortable owning the challenge lifecycle can use direct API delivery; an SMTP-only login library needs an adapter or an SMTP-capable provider. For the seller waiting on an order alert, the useful result is a traceable message and a working login, not a smaller credential spreadsheet.

References

Top comments (0)