Sheets & data
Validate emails and phone numbers in Excel
Check an email column of an Excel table with an Office Script that writes status columns, through a small relay that keeps the API key out of the workbook.
Updated 2026-11-26
This recipe adds status columns to an Excel table of contacts. You run an Office Script, it sends the emails that have no status yet in groups of 100, and it writes Email status and Email detail next to each row. There is no Qelka add-in for Excel, and an Office Script cannot call the API directly, so the script talks to a small relay you deploy once. The relay holds the API key and forwards each group to the batch endpoint.
What you need
- Excel for the web with the Automate tab, which needs a Microsoft 365 business or education license that includes Office Scripts, or the preview for personal plans. If the tab is missing, your admin may have turned Office Scripts off.
- The emails in an Excel table (Insert, then Table) named
Contacts, with a column namedEmail. - A place to run the relay. The example is a Cloudflare Worker, which the Cloudflare Workers integration covers in detail; any HTTPS server of yours works the same way.
- A Qelka API key for the relay. Build with a
sk_test_key: it returns simulated results and never spends credits, see Test mode. For the live key, restrict it tobatch,emailandphonein the dashboard, so a leak cannot start a bulk job: see Restricted keys.
Why a relay
Two facts from Microsoft's documentation shape this recipe:
- In Excel for the web, a script's
fetchcall is subject to cross-origin rules: the server it calls must answer with anAccess-Control-Allow-Originheader. The API sends no such header, because it is designed to be called from servers. Its keys must never sit in browser code: see Authentication. - Office Scripts has no infrastructure to store keys. Microsoft states that credentials have to be hardcoded or read from another source, and a script is a file anyone with access can open.
The relay solves both. It answers the browser with the right headers, keeps the API key as a server secret, and accepts only email and phone checks, so the token in the script cannot do anything else.
Steps
1. Deploy the relay
Create a Worker project and save this as src/index.js:
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'content-type, x-relay-token',
'Access-Control-Expose-Headers': 'x-request-id',
'Access-Control-Max-Age': '86400',
}
function reply(body, status) {
return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } })
}
function toItem(item) {
if (item?.type === 'email' && typeof item.email === 'string') {
return { type: 'email', email: item.email, mode: item.mode === 'fast' ? 'fast' : 'full' }
}
if (item?.type === 'phone' && typeof item.phone === 'string') {
return typeof item.country === 'string' && item.country
? { type: 'phone', phone: item.phone, country: item.country }
: { type: 'phone', phone: item.phone }
}
return null
}
export default {
async fetch(request, env) {
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders })
if (request.method !== 'POST') return reply({ error: { type: 'invalid_request', message: 'POST only' } }, 405)
if (!env.RELAY_TOKEN || request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {
return reply({ error: { type: 'relay_unauthorized', message: 'Wrong relay token' } }, 401)
}
const body = await request.json().catch(() => null)
const items = Array.isArray(body?.items) ? body.items.map(toItem) : []
if (items.length === 0 || items.length > 100 || items.includes(null)) {
return reply({ error: { type: 'invalid_request', message: 'Send 1 to 100 email or phone items' } }, 400)
}
for (let attempt = 1; attempt <= 3; attempt += 1) {
let upstream
try {
upstream = await fetch('https://api.qelka.com/v1/batch', {
method: 'POST',
headers: { Authorization: `Bearer ${env.API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ items }),
signal: AbortSignal.timeout(30000),
})
} catch {
return reply({ error: { type: 'relay_unreachable', message: 'The API did not answer' } }, 502)
}
if ([429, 500, 502, 503].includes(upstream.status) && attempt < 3) {
const retryAfter = Number(upstream.headers.get('Retry-After'))
await new Promise((resolve) => setTimeout(resolve, (retryAfter > 0 ? Math.min(retryAfter, 10) : attempt * 2) * 1000))
continue
}
const requestId = upstream.headers.get('X-Request-Id') ?? ''
if (!upstream.ok) console.log(`batch failed ${upstream.status} request ${requestId}`)
return new Response(upstream.body, {
status: upstream.status,
headers: { ...corsHeaders, 'Content-Type': 'application/json', 'X-Request-Id': requestId },
})
}
},
}
Store the two secrets and deploy:
npx wrangler secret put API_KEY
npx wrangler secret put RELAY_TOKEN
npx wrangler deploy
Wrangler prompts for each value, so neither lands in a file or your shell history. For RELAY_TOKEN, use a long random string such as the output of openssl rand -hex 32. Note the Worker's URL that wrangler deploy prints.
Access-Control-Allow-Origin is * because Microsoft warns that the origin of the Office Scripts runtime can change without notice; the relay token, not the origin, is what protects it. Emails go out in full mode by default, mailbox check included; the relay accepts fast when the script asks for it.
2. Create the script
In Excel for the web, open the workbook, go to the Automate tab, select New Script and open a blank script in the Code Editor. Replace its contents:
const RELAY_URL = 'https://validation-relay.your-account.workers.dev'
const RELAY_TOKEN = 'paste-the-relay-token'
const TABLE_NAME = 'Contacts'
const EMAIL_COLUMN = 'Email'
const EMAIL_MODE = 'full'
const CHUNK_SIZE = 100
interface ApiError {
type: string
message: string
}
interface ResultItem {
object: string
status?: string
reason?: string
did_you_mean?: string | null
error?: ApiError
}
interface BatchReply {
data?: ResultItem[]
error?: ApiError
}
async function main(workbook: ExcelScript.Workbook): Promise<void> {
const table = workbook.getTable(TABLE_NAME)
if (!table) {
console.log(`No table named ${TABLE_NAME}`)
return
}
const source = table.getColumnByName(EMAIL_COLUMN)
if (!source) {
console.log(`No column named ${EMAIL_COLUMN}`)
return
}
const statusColumn = table.getColumnByName('Email status') ?? table.addColumn(-1, null, 'Email status')
const detailColumn = table.getColumnByName('Email detail') ?? table.addColumn(-1, null, 'Email detail')
const statusRange = statusColumn.getRangeBetweenHeaderAndTotal()
const detailRange = detailColumn.getRangeBetweenHeaderAndTotal()
const emails = source.getRangeBetweenHeaderAndTotal().getValues().map((row) => String(row[0]).trim())
const statuses = statusRange.getValues().map((row) => String(row[0]))
const details = detailRange.getValues().map((row) => String(row[0]))
const pending: number[] = []
emails.forEach((email, index) => {
if (email !== '' && (statuses[index] === '' || statuses[index] === 'unchecked')) pending.push(index)
})
for (let start = 0; start < pending.length; start += CHUNK_SIZE) {
const rows = pending.slice(start, start + CHUNK_SIZE)
const reply = await callRelay(rows.map((index) => emails[index]))
rows.forEach((rowIndex, position) => {
const item = reply.data ? reply.data[position] : undefined
if (!item || item.object === 'error') {
statuses[rowIndex] = 'unchecked'
details[rowIndex] = item && item.error ? item.error.type : reply.error ? reply.error.type : 'unreachable'
} else {
statuses[rowIndex] = item.status ?? 'unchecked'
details[rowIndex] = item.did_you_mean ?? item.reason ?? ''
}
})
statusRange.setValues(statuses.map((value) => [value]))
detailRange.setValues(details.map((value) => [value]))
}
console.log(`Checked ${pending.length} rows`)
}
async function callRelay(emails: string[]): Promise<BatchReply> {
try {
const response = await fetch(RELAY_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Relay-Token': RELAY_TOKEN },
body: JSON.stringify({ items: emails.map((email) => ({ type: 'email', email, mode: EMAIL_MODE })) }),
})
const reply: BatchReply = await response.json()
if (!response.ok) {
const type = reply.error ? reply.error.type : String(response.status)
console.log(`Batch failed: ${type}, request ${response.headers.get('X-Request-Id')}`)
}
return reply
} catch {
console.log('Relay unreachable')
return {}
}
}
Set RELAY_URL and RELAY_TOKEN, then select Run. The script adds the two columns if they are missing, skips rows that already have a status, and writes the results after each group, so a long table that stops halfway keeps what was done. Running it again checks only new rows and rows marked unchecked.
Office Scripts requires a typed interface for JSON read with fetch, because it does not allow the any type: that is what ResultItem and BatchReply are for. Logs appear in the Output tab of the Code Editor.
3. Mind where the script lives
A script is saved in your OneDrive, in Documents, Office Scripts, not inside the workbook. If you associate it with the workbook so colleagues can run it, everyone with access to the workbook can open it and read the relay token. That is acceptable only because the token is not your API key and the relay accepts nothing but email and phone checks. Still:
- Build with a test key in the relay, and switch the relay to the live, restricted key once the script works.
- Do not share the workbook outside the people who need the script, and never paste the API key itself into a script or a cell.
- If the token leaks, change
RELAY_TOKENwithwrangler secret putand update the script.
Read the columns
Email status |
Meaning | What to do |
|---|---|---|
deliverable |
The mail server accepted the mailbox | Keep |
undeliverable |
Bad syntax, no domain or no mailbox | Remove, or fix with the suggestion in Email detail |
risky |
Disposable inbox, catch-all domain or full mailbox | Read Email detail for the reason, then decide |
unknown |
The checks could not conclude | Keep: not a bad address |
unchecked |
The check did not run; Email detail holds the error type |
Run the script again later |
Add a conditional formatting rule on Email status to color undeliverable rows. To check phone numbers instead, send items of type phone, with a country taken from another column when numbers lack the + prefix, and write e164 from each result. See the email reference and the phone reference.
Handle errors and rate limits
Nothing is billed on errors. The relay retries 429, 500, 502 and 503 after Retry-After, then passes the API's error to the script, which marks the rows unchecked with the error type in Email detail and logs the request id. 401 invalid_api_key and 403 forbidden point at the relay's key, 402 insufficient_credits at an empty balance, and relay_unauthorized at a wrong relay token in the script. One item that cannot be checked does not fail its group: it comes back as an error item and only that row is marked. See Errors.
A batch counts as one request against the 200 requests per 10 seconds of a key, and each email costs 1 credit, the same in full and fast mode. Microsoft limits each request and response between a script and the workbook to 5 MB, which a table of a few thousand rows stays well under. For files of tens of thousands of rows, export the column to CSV and run a bulk job instead: it runs in the background and needs no script.
Related
Frequently asked questions
Why not call the API straight from the Office Script?
Where does the API key go?
Can I run the script from Power Automate or on a schedule?
More in Sheets & data
All integrationsPut this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time