Skip to content

Guide · Nexbit Send

Sending sign-in codes and OTPs by email that arrive on time

Design email sign-in codes that arrive while still valid: expiry, idempotency keys, retries, rate limits, templates and webhook monitoring, with code in curl, Node, PHP, Python and Go.

The Nexbit teamUpdated 8 min read

A one-time code is the most time-sensitive email most products send. The customer is looking at your sign-in screen, phone in hand, waiting. If the code takes three minutes, they press "resend", get a second code, type the first one, fail, and call support. This guide covers how to design the whole flow, not just the email, so codes arrive quickly, work when they arrive, and are safe.

The flow at a glance

  1. The person enters their email address and asks for a code.
  2. Your server checks rate limits, creates a code, stores a hash of it with an expiry, and sends the email with an idempotency key.
  3. The sending service accepts the request immediately and delivers the email.
  4. The person types the code; your server checks it against the hash, the expiry and the attempt count, and signs them in.
  5. Your server listens for delivery events, so support can see what happened to any code.

Each step has decisions that affect whether the code is still useful when it arrives.

Designing the code

  • Length. Six digits is the common choice: easy to type on a phone, and with a sensible attempt limit, hard to guess. Use a cryptographically secure random number source, never a timestamp or a counter.
  • Expiry. Ten minutes is a reasonable default for email. Shorter expiries look safer, but email can be delayed by a minute or two by receiving servers, and an expired code is a support call.
  • Attempts. Allow five wrong attempts per code, then require a new one.
  • Earlier codes. When a new code is sent, keep the previous one valid until it expires. People often type the first code that arrives, and invalidating it causes most "the code doesn't work" complaints.
  • Storage. Store a hash of the code (for example HMAC-SHA256 with a server secret), never the code itself, along with the email, expiry and attempt count.

Rate limits

Without limits, a sign-in form becomes a way to flood someone's inbox, or to run up your email bill. Limit at several levels:

  • Per email address: for example one code per 60 seconds and five per hour.
  • Per IP address: a higher limit, to catch one person trying many addresses.
  • Globally: an alarm if total code requests jump far above normal.

Show the person a countdown before they can resend ("You can ask for a new code in 45 seconds"). It reduces resends and tells them the first email is on its way.

Sending: idempotency keys

Networks fail. Your server may send the request, the sending service may accept it, and the response may be lost on the way back. If your code then retries, the person gets two emails with two different codes.

An idempotency key fixes this. You send a unique key with the request, such as the code's own record id; if the same key arrives again, the sending service returns the original result instead of sending a second email. Nexbit Send accepts an Idempotency-Key header on every request that sends mail.

Use a key that identifies this particular code, not the person: otp-<code record id> is ideal.

Sending: the request

Here is the same request in five languages. Each sends the code from a transactional stream with a template, a tag for reporting and an idempotency key. Replace the API key, domain and template id with your own; the API address is shown in your Nexbit Send dashboard.

curl

curl https://api.send.getnexbit.com/v1/messages \
  -H "Authorization: Bearer $NEXBIT_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: otp-7f3c2a" \
  -d '{
    "from": "Acme <[email protected]>",
    "to": ["[email protected]"],
    "template_id": "tpl_signin_code",
    "template_data": { "code": "482913", "minutes": 10 },
    "stream": "transactional",
    "tags": { "type": "otp" }
  }'

Node.js

const res = await fetch("https://api.send.getnexbit.com/v1/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.NEXBIT_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": `otp-${codeRecord.id}`,
  },
  body: JSON.stringify({
    from: "Acme <[email protected]>",
    to: [email],
    template_id: "tpl_signin_code",
    template_data: { code, minutes: 10 },
    stream: "transactional",
    tags: { type: "otp" },
  }),
  signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error((await res.json()).error.message);

PHP

$ch = curl_init('https://api.send.getnexbit.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 5,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('NEXBIT_API_KEY'),
        'Content-Type: application/json',
        'Idempotency-Key: otp-' . $codeRecordId,
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'from' => 'Acme <[email protected]>',
        'to' => [$email],
        'template_id' => 'tpl_signin_code',
        'template_data' => ['code' => $code, 'minutes' => 10],
        'stream' => 'transactional',
        'tags' => ['type' => 'otp'],
    ]),
]);
$body = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 202) {
    throw new RuntimeException($body ?: curl_error($ch));
}

Python

import os
import requests

res = requests.post(
    "https://api.send.getnexbit.com/v1/messages",
    headers={
        "Authorization": f"Bearer {os.environ['NEXBIT_API_KEY']}",
        "Idempotency-Key": f"otp-{code_record.id}",
    },
    json={
        "from": "Acme <[email protected]>",
        "to": [email],
        "template_id": "tpl_signin_code",
        "template_data": {"code": code, "minutes": 10},
        "stream": "transactional",
        "tags": {"type": "otp"},
    },
    timeout=5,
)
res.raise_for_status()

Go

body, _ := json.Marshal(map[string]any{
	"from":          "Acme <[email protected]>",
	"to":            []string{email},
	"template_id":   "tpl_signin_code",
	"template_data": map[string]any{"code": code, "minutes": 10},
	"stream":        "transactional",
	"tags":          map[string]string{"type": "otp"},
})
req, _ := http.NewRequestWithContext(ctx, "POST", "https://api.send.getnexbit.com/v1/messages", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("NEXBIT_API_KEY"))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "otp-"+codeRecordID)
res, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)

A successful request returns 202 Accepted with a message id. Store that id with the code record so you can look it up later.

Retries on your side

If the request fails with a network error, a timeout or a 5xx response, retry with the same idempotency key two or three times with a short delay (half a second, then two seconds). If it fails with 429, wait as the response asks and then retry. Any other 4xx should not be retried: read the error, which says what is wrong (an unverified domain, a missing field, a suppressed address).

Do not retry because the email "hasn't arrived yet". Once the sending service has accepted the message, it handles retries to the receiving server itself; Nexbit Send retries temporary failures for up to 3 days, although for a code the expiry will have passed long before that.

The template

A code email should be readable in two seconds:

  • Subject: put the code in it, with your product name: "482913 is your Acme sign-in code". Many people never open the email; they read the code from the notification.
  • First line: the code again, large, in a monospaced font, with nothing around it that could be mistaken for part of it.
  • Expiry: "This code expires in 10 minutes."
  • Context: "Someone asked to sign in to Acme with this address. If it wasn't you, you can ignore this email."
  • No links unless they are needed. Never include a link that signs the person in directly in the same email as the code; pick one method.
  • A plain-text part, always.

Keep code emails free of marketing. Send them from a transactional subdomain and stream.

Making delivery fast

Most delay in code delivery is not in sending; it is in the receiving servers. You can still help:

  1. Authenticate properly. Unauthenticated mail is slowed down and filtered. Follow the SPF, DKIM and DMARC guide.
  2. Keep codes on their own stream. Codes should never wait behind a newsletter in a queue.
  3. Send consistently. A domain that sends codes steadily builds a stable reputation; sudden bursts are throttled.
  4. Avoid bounces. Validate email addresses at sign-up (syntax and a typo check for common domains), and suppress addresses that bounced.
  5. Keep the email small. No large images or attachments.

Monitoring with webhooks

Subscribe to delivery events, and store them against the message id you saved:

  • message.delivered: the receiving server accepted it. Store the time.
  • message.deferred: the receiver asked to try later. If this happens often for one provider, look at your reputation with them.
  • message.bounced: the address does not exist or the receiver refused it. Show the person a message to check their address.
  • message.complained: the person marked it as spam. Rare for codes; worth investigating if it is not.

Every webhook from Nexbit Send is signed with HMAC-SHA256 in a Nexbit-Signature header, which you should verify before trusting the body.

With this in place, support can answer "I didn't get my code" with facts: "Your provider accepted it at 10:42:07. Please check your spam folder" or "Your provider rejected it: the address doesn't exist. Could there be a typo?"

Useful numbers to watch daily:

  • the time from request to message.delivered, at the median and the slowest 5%;
  • the share of codes that are never used;
  • bounces and deferrals by receiving provider.

Security checklist

  1. Codes come from a secure random source and are stored only as hashes.
  2. Codes expire (10 minutes is a good default) and allow a limited number of attempts.
  3. Requests are rate-limited per address, per IP and globally.
  4. The sign-in screen gives the same response whether or not the address has an account, so it cannot be used to discover customers.
  5. Codes are never written to logs, analytics or error trackers.
  6. Webhook signatures are verified before acting on events.
  7. A code sent for one purpose (sign-in) cannot be used for another (changing the email address).

Should you use email at all?

Email codes are convenient and need no phone number, but an inbox is only as safe as its password. For high-value actions, such as moving money or changing payout details, combine email with a second factor the person controls, such as an authenticator app or a passkey, and keep email codes for sign-in and verification.

For a complete setup in Nexbit Send, see the sign-in codes use case and the sending docs.