Fetch verification codes in tests
Extract OTP and verification codes from captured emails using the API. Automate MFA and confirmation flows in your test suite.
The problem
Multi-factor authentication and email confirmation flows send one-time codes. Automated tests need to extract these codes to complete verification steps, but parsing email content manually is error-prone.
How ammo.tools solves it
The API includes a dedicated endpoint that extracts verification codes from captured emails. It recognises common formats like "Your code is 123456" or "OTP: 1234" and returns the codes with their context.
Setup
- Configure your application to send emails through ammo.tools SMTP.
- Trigger the verification flow in your test.
- Fetch the message and extract codes via the API.
Extract codes from a message
curl -H "Authorization: Bearer $AMMO_TOOLS_API_KEY" \ "https://app.ammo.tools/api/v1/messages/MSG_ID/codes"
Response format
{
"items": [
{
"value": "482951",
"source": "html",
"context": "Your verification code is 482951"
}
]
}
Python example
import os, requests
api = "https://app.ammo.tools/api/v1"
key = os.environ["AMMO_TOOLS_API_KEY"]
headers = {"Authorization": f"Bearer {key}"}
# Wait for the verification email
resp = requests.get(
f"{api}/inboxes/{inbox_id}/messages",
params={"to": "user@example.test", "wait": 30},
headers=headers,
)
msg_id = resp.json()["items"][0]["id"]
# Extract the code
codes = requests.get(f"{api}/messages/{msg_id}/codes", headers=headers).json()["items"]
otp = codes[0]["value"] # e.g. "482951"
# Use otp to complete verification in your test
JavaScript example
const api = "https://app.ammo.tools/api/v1";
const key = process.env.AMMO_TOOLS_API_KEY;
const messages = await fetch(
`${api}/inboxes/${inboxId}/messages?to=user@example.test&wait=30`,
{ headers: { Authorization: `Bearer ${key}` } }
).then(r => r.json());
const msgId = messages.items[0].id;
const codes = await fetch(`${api}/messages/${msgId}/codes`, {
headers: { Authorization: `Bearer ${key}` }
}).then(r => r.json());
const otp = codes.items[0].value;
Things to know
- The API extracts numeric codes from common patterns: OTP, verification code, confirmation code, security code.
- Codes are extracted from the subject, plain-text body and HTML body.
- The
sourcefield indicates where the code was found. - The
contextfield shows the surrounding text for verification. - Up to 20 codes are returned per message.