// email-validation.org for Botpress: the code of an Execute Code card that checks the address a Capture Information // card saved, and writes the verdict to workflow variables an Expression card can branch on. // Paste this whole file into an Execute Code card placed after the Capture Information card (type Email Address). // Before it runs, create these Workflow variables of type String: emailDecision, emailStatus, emailReason and // emailSuggestion. After it, add an Expression card with the condition workflow.emailDecision === 'flagged'. // The API key is never in this code: it comes from the configuration variable EMAIL_VALIDATION_API_KEY (Bot Settings, // Configuration Variables; Botpress keeps them encrypted). It goes only to our two API hosts and never into a // variable. The card logs nothing and never throws: when the check cannot be made, emailDecision is 'unchecked'. // ---- Settings ---- // The address to check: the Workflow variable the Capture Information card saved it in (here userEmail). const givenAddress = typeof workflow === 'object' && workflow !== null ? workflow.userEmail : undefined; const apiHost = 'https://api.email-validation.org'; // EU data residency: const apiHost = 'https://api-eu.email-validation.org'; // The statuses that make emailDecision 'flagged'. Add 'catch_all' or 'unknown' to flag those too; remove // 'disposable' to let throwaway inboxes through. const flagStatuses = ['invalid', 'disposable']; // How long to wait for our answer, in whole milliseconds from 1 to 30000: well inside the 60 seconds Botpress gives // a bot to handle a message. Under about 7000 a check our API is still answering (it answers within 5 seconds) may be // cut off here and still counted. const timeoutMs = 10000; // ---- End of settings ---- const statuses = ['valid', 'invalid', 'catch_all', 'unknown', 'disposable']; const flaggable = ['invalid', 'catch_all', 'unknown', 'disposable']; // An unknown for our own timeout or failure says nothing about the address: never flagged, never allowed. const neverFlagReasons = ['timeout', 'internal_error']; // Our error codes: any other code in an error reply becomes http_, so a reply cannot put words into a variable. const errorCodes = [ 'invalid_request', 'unauthorized', 'insufficient_credits', 'forbidden', 'forbidden_origin', 'not_found', 'conflict', 'length_required', 'payload_too_large', 'rate_limited', 'abuse_throttled', 'key_daily_cap', 'internal_error', 'service_unavailable', 'upstream_capacity', ]; // Our reasons: any other reason in a reply is dropped, so a reply cannot put words into the conversation. const reasons = [ 'accepted', 'alias', 'normalized', 'low_engagement', 'high_engagement', 'trusted_catch_all', 'ai_agent', 'role_account', 'abuse_linked', 'suppressed', 'trap_pattern', 'spamtrap', 'complainer', 'no_mailbox', 'no_inbound_mail', 'invalid_syntax', 'likely_typo', 'no_dns', 'mailbox_full', 'unroutable', 'catch_all', 'role_catch_all', 'forwarding_domain', 'disposable', 'server_unavailable', 'temporary_error', 'greylisted', 'anti_spam_block', 'timeout', 'internal_error', ]; // One address only: no spaces or control characters, nothing of a link (":", "/", "?", "#"), nothing that wraps or // lists addresses ("<", ">", "(", ")", '"', ",", ";"), a dot in the domain. A link with an @ in it // (https://example.com/@name, example.com/@name) or a mailto: is never sent or suggested. const addressRule = /^[^\s@:/?#<>()",;]+@[^\s@:/?#<>()",;]+\.[^\s@.:/?#<>()",;]{2,}$/; // A control character (below a space, or DEL) anywhere: never an address. const hasControl = (value) => [...value].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127); const isAddress = (value) => typeof value === 'string' && value.length <= 254 && !hasControl(value) && addressRule.test(value); const checkEmail = async () => { const result = { decision: 'unchecked', status: '', reason: '', suggestion: '' }; const unchecked = (why) => { result.reason = why; return result; }; // The key goes only to our two API hosts. if (apiHost !== 'https://api.email-validation.org' && apiHost !== 'https://api-eu.email-validation.org') { return unchecked('bad_setting'); } if (!Array.isArray(flagStatuses) || !flagStatuses.every((s) => flaggable.includes(s))) { return unchecked('bad_setting'); } if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000) { return unchecked('bad_setting'); } const raw = typeof env === 'object' && env !== null ? env.EMAIL_VALIDATION_API_KEY : undefined; const key = typeof raw === 'string' ? raw.trim() : ''; // Printable ASCII only: anything else could not be sent as a header. if (!/^[\x21-\x7e]{1,512}$/.test(key)) { return unchecked('missing_key'); } // True when a value holds the key or any 12 characters of it in a row: such a value never reaches a variable. const holdsKey = (value) => { if (key.length < 12) return value.includes(key); for (let i = 0; i + 12 <= key.length; i++) { if (value.includes(key.slice(i, i + 12))) return true; } return false; }; const address = typeof givenAddress === 'string' ? givenAddress.trim() : ''; if (!isAddress(address)) { return unchecked('not_an_address'); } if (typeof axios !== 'function' && (typeof axios !== 'object' || axios === null)) { return unchecked('no_axios'); } if (typeof axios.post !== 'function') { return unchecked('no_axios'); } let reply = null; try { // One call per run, never retried: the check may have counted. reply = await axios.post( `${apiHost}/v1/validate`, // The API's shortest check time in seconds: a check that needs longer ends as a free unknown (reason timeout). JSON.stringify({ email: address, timeout: 5 }), { headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': 'email-validation-botpress/1.0.0', }, timeout: timeoutMs, // axios's timeout covers a silent connection; the signal also ends a reply that trickles in. ...(typeof AbortSignal === 'function' && typeof AbortSignal.timeout === 'function' ? { signal: AbortSignal.timeout(timeoutMs) } : {}), // A redirect is never followed, so the key never leaves our hosts. maxRedirects: 0, // Every HTTP status is an answer to read, not an error to throw. validateStatus: () => true, // The body as it came, parsed below. responseType: 'text', transformResponse: [(data) => data], }, ); } catch (err) { const code = typeof err === 'object' && err !== null ? err.code : ''; const late = code === 'ECONNABORTED' || code === 'ETIMEDOUT' || code === 'ERR_CANCELED'; return unchecked(late ? 'timeout' : 'connection_error'); } if (typeof reply !== 'object' || reply === null) { return unchecked('connection_error'); } let body = reply.data; if (typeof body === 'string') { try { body = JSON.parse(body); } catch { body = null; } } if (typeof body !== 'object' || body === null || Array.isArray(body)) body = {}; const httpCode = Number.isInteger(reply.status) ? reply.status : 0; if (httpCode !== 200) { const envelope = typeof body.error === 'object' && body.error !== null && !Array.isArray(body.error) ? body.error : {}; const code = typeof envelope.code === 'string' && errorCodes.includes(envelope.code) ? envelope.code : ''; return unchecked(code || `http_${httpCode}`); } const status = typeof body.status === 'string' ? body.status : ''; if (!statuses.includes(status)) { return unchecked('unexpected_response'); } const reason = typeof body.reason === 'string' && reasons.includes(body.reason) ? body.reason : ''; if (status === 'unknown' && neverFlagReasons.includes(reason)) { return unchecked(reason); } const suggestion = typeof body.did_you_mean === 'string' ? body.did_you_mean.trim() : ''; result.status = status; result.reason = reason; result.suggestion = isAddress(suggestion) && !holdsKey(suggestion) ? suggestion : ''; const disposable = body.disposable === true; result.decision = flagStatuses.includes(status) || (flagStatuses.includes('disposable') && disposable) ? 'flagged' : 'allowed'; return result; }; let verdict = { decision: 'unchecked', status: '', reason: 'card_error', suggestion: '' }; try { verdict = await checkEmail(); } catch { // Never stop the conversation: a fault here leaves the address unchecked. } // Each write on its own: a variable created with another type than String makes Botpress throw on that write, and // the card still never stops the conversation. if (typeof workflow === 'object' && workflow !== null) { try { workflow.emailDecision = verdict.decision; } catch {} try { workflow.emailStatus = verdict.status; } catch {} try { workflow.emailReason = verdict.reason; } catch {} try { workflow.emailSuggestion = verdict.suggestion; } catch {} }