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 (
secretsin Python,crypto.randomIntin Node), neverrandom. - 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 554is easier than318554. 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
randominstead ofsecrets. 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.