Sheets & data
Validate emails in Snowflake with a Python UDF
Verify emails from SQL in Snowflake: a network rule, a secret and an external access integration, then a Python UDF that calls POST /email and returns the status.
Updated 2026-11-26
This recipe lets you verify email addresses from SQL in Snowflake. You allow outbound calls to the API with an external access integration, store the API key as a Snowflake secret, and create a Python UDF that sends an address to POST /email and returns its status. Then SELECT verify_email(email) FROM ... works like any function. There is no Qelka app in the Snowflake Marketplace: everything below runs in your account.
What you need
- A Snowflake account with external access. Snowflake disables it by default on trial accounts.
- A role with the CREATE INTEGRATION privilege on the account (ACCOUNTADMIN by default) for step 1, and a role that can create functions and secrets in your schema.
- A warehouse for the queries, and the table of emails to check.
- A Qelka API key. A
sk_test_key returns simulated results and never spends credits: see Test mode. Use a key restricted toemailin the dashboard: see Restricted keys.
Steps
1. Allow the API host
Run as a role with CREATE INTEGRATION, in the database and schema where the function will live:
CREATE OR REPLACE NETWORK RULE validation_api_rule
MODE = EGRESS
TYPE = HOST_PORT
VALUE_LIST = ('api.qelka.com');
CREATE OR REPLACE SECRET validation_api_key
TYPE = GENERIC_STRING
SECRET_STRING = 'sk_test_paste_your_key';
CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION validation_api_access
ALLOWED_NETWORK_RULES = (validation_api_rule)
ALLOWED_AUTHENTICATION_SECRETS = (validation_api_key)
ENABLED = TRUE;
The network rule allows only the API's host, on port 443 since no port is given. The integration ties that host to the one secret allowed to travel there. Paste the key in a worksheet you do not share or save, then replace it with the live key later with ALTER SECRET validation_api_key SET SECRET_STRING = '...'.
If another role will create the function, grant it what Snowflake requires:
GRANT USAGE ON INTEGRATION validation_api_access TO ROLE data_engineer;
GRANT READ ON SECRET validation_api_key TO ROLE data_engineer;
That role also needs USAGE on the secret's database and schema.
2. Create the function
CREATE OR REPLACE FUNCTION verify_email(email STRING)
RETURNS STRING
LANGUAGE PYTHON
RUNTIME_VERSION = 3.12
HANDLER = 'verify'
EXTERNAL_ACCESS_INTEGRATIONS = (validation_api_access)
SECRETS = ('api_key' = validation_api_key)
PACKAGES = ('snowflake-snowpark-python', 'requests')
AS
$$
import logging
import time
import requests
from snowflake.snowpark import secrets
logger = logging.getLogger("verify_email")
session = requests.Session()
RETRYABLE = {429, 500, 502, 503}
def verify(email):
if email is None or email.strip() == "":
return None
api_key = secrets.get_generic_secret_string("api_key")
for attempt in range(1, 4):
try:
response = session.post(
"https://api.qelka.com/v1/email",
headers={"Authorization": f"Bearer {api_key}"},
json={"email": email.strip(), "mode": "fast"},
timeout=10,
)
except requests.RequestException:
logger.warning("validation skipped: unreachable")
return "unchecked"
if response.status_code == 200:
return response.json()["status"]
if response.status_code in RETRYABLE and attempt < 3:
retry_after = response.headers.get("Retry-After", "")
time.sleep(min(int(retry_after), 5) if retry_after.isdigit() else attempt)
continue
try:
error_type = response.json()["error"]["type"]
except (ValueError, KeyError, TypeError):
error_type = f"http_{response.status_code}"
logger.warning(
"validation skipped: %s request %s", error_type, response.headers.get("X-Request-Id")
)
return "unchecked"
return "unchecked"
$$;
How it behaves:
SECRETSbinds the Snowflake secret to the nameapi_key, which the handler reads withsecrets.get_generic_secret_string. The key never appears in the function's definition.- The
requests.Sessionis created once per process and reused across rows, so connections to the API are kept open. mode: 'fast'skips the mailbox check, which can wait seconds on a slow mail server while your warehouse keeps billing. Fast mode still catches bad syntax, dead domains and disposable inboxes, but cannot returndeliverable: a clean address comes backunknown, reasonsmtp_not_checked. Use a bulk job infullmode when you need mailbox-level answers. See the email reference.- Any API problem returns
uncheckedinstead of failing the whole query. If your account has an event table and a log level that keeps warnings, the error type and request id land there.
Try it:
SELECT verify_email('disposable@example.com');
With a test key, the answer is risky.
3. Store results instead of recomputing them
Calling the function in a view or a dashboard query would check the same addresses again on every refresh, and each check costs 1 credit. Keep one row per address in a table, and only check addresses it does not have yet:
CREATE TABLE IF NOT EXISTS email_checks (
email STRING,
status STRING,
checked_at TIMESTAMP_NTZ
);
DELETE FROM email_checks WHERE status = 'unchecked';
INSERT INTO email_checks (email, status, checked_at)
SELECT email, verify_email(email), CURRENT_TIMESTAMP()
FROM (
SELECT DISTINCT LOWER(TRIM(s.email)) AS email
FROM signups AS s
WHERE s.email IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM email_checks AS c WHERE c.email = LOWER(TRIM(s.email))
)
LIMIT 1000
) AS batch;
The LIMIT inside the subquery caps how many addresses one run checks, so a mistake costs at most 1,000 checks. Rows marked unchecked are deleted first so they are tried again. Run the statement from a Snowflake task on a schedule to check new signups as they arrive, then join email_checks wherever you need the status.
4. Use a bulk job for big tables
A UDF sends one request per row. That suits new rows every day, not a first pass over millions of addresses. For a large table, unload the distinct emails to a CSV file, upload it as a bulk job, and load the result file back into email_checks. A bulk job takes up to 2,000,000 rows per file, runs in the background without a warehouse waiting on it, can use full mode, and reserves 1 credit per row up front, returning what it does not use.
Read the status
| Status | Meaning | What to do |
|---|---|---|
undeliverable |
Bad syntax, no domain, or a domain that takes no mail | Exclude from sends; fix at the source |
risky |
Disposable inbox (in fast mode, the main risky case) |
Exclude from trials and incentives |
unknown |
Passed the fast checks, or not conclusive | Keep: not a bad address |
deliverable |
Not returned in fast mode | Run a bulk job in full mode to get it |
unchecked |
The API did not answer, or refused the call | Deleted and retried on the next run |
NULL |
Empty input | Nothing to check |
To keep the reason or the suggested correction as well, return VARIANT instead of STRING and pass response.json() back, then read result:reason and result:did_you_mean in SQL.
Handle errors and rate limits
Nothing is billed on errors. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key in the secret, 402 insufficient_credits an empty balance: every row then comes back unchecked, so check a few rows before a large run. 429 rate_limited, 500, 502 and 503 are retried after Retry-After, capped at five seconds. Snowflake runs the handler in several processes at once, and a key allows 200 requests per 10 seconds, so a large warehouse can reach the limit: a smaller warehouse or a lower LIMIT per run keeps you under it. See Errors and Rate limits.
For thousands of rows per run, a vectorized Python UDF can send each batch Snowflake hands it to the batch endpoint, up to 100 addresses per request, which counts as one request against the rate limit.
Related
Frequently asked questions
How much does this cost?
Where is the API key stored?
Why does my account refuse CREATE EXTERNAL ACCESS INTEGRATION?
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