Use-cases

OTP and verification code emails: how to send them safely

Short answer

An OTP email sends a short one-time code, usually six digits, that proves the user controls an email address or confirms a sign-in. Generate it with a secure random function, store a hash, expire it in about 10 minutes, and lock it after a few wrong attempts. Put the code in the subject or first line, send it from a verified domain through a transactional API, and never reuse it.

Last checked 16 November 2026

An OTP email sends a one-time code, usually six digits, that the user types back into your app. It proves they control the address, at sign-up, at login, or before a sensitive action like changing a payout account. The code must be random, short-lived and single-use, and the email must arrive within seconds, because the user is staring at an input box waiting for it.

When to use an email code

Use Code or link?
Verifying an address at sign-up Either; a code avoids switching tabs on mobile
Passwordless login Code works across devices; a link is one click on the same device
Confirming a risky action Code, entered in the same session
Strong multi-factor authentication Neither: prefer passkeys or an authenticator app

On that last row: NIST SP 800-63B (section 5.1.3.1) says methods that do not prove possession of a specific device, such as email, shall not be used for out-of-band authentication. Email codes prove address control. They are fine for that.

Rules for the code

  • Random. Use a cryptographically secure generator (secrets in Python, crypto.randomInt in Node), never random.
  • Six digits. Long enough with an attempt limit, short enough to type.
  • Hash it. Store a hash with the user id, purpose and expiry, not the code itself.
  • Expire it. About 10 minutes.
  • Limit attempts. Lock the code after around five wrong guesses and make the user request a new one.
  • One purpose. A sign-up code must not work for a payout change.
  • Rate limit sending. For example one code a minute and a handful an hour per address.

Best practices for the email

  • Put the code where it is seen first: the first line, and optionally the subject.
  • Format it for reading: 318 554 is easier than 318554. Accept both when it is typed.
  • Say what it is for and how long it lasts.
  • Tell people what to do if they did not ask for it.
  • Keep it short, with no images or marketing. Filters and readers both like plain login mail.

OTP email template

From: Acme <verify@acme.com>
Subject: 318 554 is your Acme verification code

Your Acme verification code is:

318 554

Enter it on the sign-up page. It expires in 10 minutes.
If you did not try to create an Acme account, ignore this email.

Sending an OTP with Python and Mailcandor

This uses only the standard library plus requests. The send is one call to the Mailcandor email API.

import hashlib, os, secrets, time
import requests

def send_otp(email: str, purpose: str, store) -> None:
    code = f"{secrets.randbelow(1_000_000):06d}"
    store.save(
        email=email,
        purpose=purpose,
        code_hash=hashlib.sha256(code.encode()).hexdigest(),
        expires_at=time.time() + 600,
        attempts=0,
    )
    pretty = f"{code[:3]} {code[3:]}"
    r = requests.post(
        "https://api.mailcandor.com/v1/emails",
        headers={"Authorization": f"Bearer {os.environ['MAILCANDOR_KEY']}"},
        json={
            "from": "Acme <verify@acme.com>",
            "to": email,
            "subject": f"{pretty} is your Acme verification code",
            "html": f"<p>Your Acme verification code is:</p><p style=\"font-size:24px\"><b>{pretty}</b></p>"
                    "<p>It expires in 10 minutes. If you did not ask for it, ignore this email.</p>",
            "text": f"Your Acme verification code is {pretty}. It expires in 10 minutes.",
            "tags": [{"name": "flow", "value": f"otp_{purpose}"}],
        },
        timeout=10,
    )
    if r.status_code != 202:
        err = r.json()["error"]
        raise RuntimeError(f"{err['type']}: {err['message']}")

def check_otp(email: str, purpose: str, typed: str, store) -> bool:
    row = store.load(email=email, purpose=purpose)
    if not row or row.expires_at < time.time() or row.attempts >= 5:
        return False
    store.increment_attempts(row)
    typed_hash = hashlib.sha256(typed.replace(" ", "").encode()).hexdigest()
    if secrets.compare_digest(typed_hash, row.code_hash):
        store.delete(row)
        return True
    return False

store is your own persistence layer. Mailcandor answers 202 with an email id straight away. If the address hard bounces, the email.bounced webhook tells you, along with a plain-English explanation of the bounce, so you can tell the user “that address does not accept mail” instead of leaving them waiting. Tags such as otp_signup let you watch delivery for each flow separately.

Protecting the key that sends codes

The code that sends OTPs runs on every login, so its API key sits in a busy, exposed service. In Mailcandor, give that service a sending-only key locked to the domain it sends from: it cannot read your logs, change DNS settings or send as another domain. Rotate it like any other secret. Before your first send, verify the domain with SPF, DKIM and DMARC, as described in our setup guide. Every plan includes unlimited domains, so a separate verify.acme.com costs nothing extra; see pricing.

Why codes arrive late, and what to do

  • Greylisting. Some receiving servers reject the first attempt from an unknown sender with a temporary error and accept the retry minutes later. A sender with a steady history is greylisted less.
  • Queues. If OTPs wait behind a newsletter in your job queue, they are late. Give login mail its own queue or send it inline.
  • Reputation. A domain that also sends marketing can be slowed or filtered. Use a separate subdomain for marketing.
  • Typos. Show the address you sent to, with a “wrong address?” link. A typo produces a hard bounce, not a late email.

Common pitfalls

  • Using random instead of secrets. Predictable codes are guessable codes.
  • No attempt limit. A million possible codes is small without one.
  • Codes that never expire. Old emails become keys.
  • Resend that does not invalidate the old code. Decide on one valid code per purpose at a time.
  • Logging the code. Request logs and error trackers keep it. Log the email id instead.

Questions

How many digits should an email OTP have?

Six digits is the common choice. It is easy to type and, with a short expiry and an attempt limit of around five, practically impossible to guess.

Is email OTP a secure second factor?

It is weaker than an authenticator app or passkey. NIST SP 800-63B does not allow email as an out-of-band authenticator, so treat email codes as proof of address control, not strong multi-factor authentication.

Why do OTP emails arrive late?

Common causes are greylisting by the receiving server, sending through a queue that is backed up, or a shared domain with poor reputation. Send immediately and keep OTP mail on a clean transactional domain.

Should I put the code in the subject line?

Many apps do, because people see it in the notification without opening the email. It also means the code appears on lock screens, so weigh that against convenience.

How do I verify an email address at sign-up?

Send a code or a link to the address, and mark the address verified only when the user enters the code or clicks the link before it expires.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.