This code works, make sure to test it on a couple first to be safe before deploying to all your contacts, and you will need to create a secret with the read write contact scopes. In the code I have written Access_Token but you can replace this with whatever your actual secret is.
/**
* Removes “additional email addresses” (hs_additional_emails) from a HubSpot contact.
* Secret: ACCESS_TOKEN (Private App token with crm.objects.contacts.read/write)
* Properties to include: hs_object_id, email
* Optional Inputs: mode (“remove_all” | “keep_allowlist”), allowlist (csv)
*/
const HUBSPOT_BASE = ‘https://api.hubapi.com’;
function maskToken(t) {
if (!t) return ‘’;
if (t.length <=
return ‘***’;
return `${t.slice(0,4)}…${t.slice(-4)} (len:${t.length})`;
}
function normalizeId(raw) {
if (raw == null) return ‘’;
const s = String(raw).trim();
// HubSpot v3 IDs are numeric strings. We accept numeric-only.
return /^\d+$/.test(s) ? s : ‘’;
}
async function fetchJson(url, opts = {}) {
const res = await fetch(url, opts);
const text = await res.text().catch(() => ‘’);
let body;
try { body = text ? JSON.parse(text) : undefined; } catch { body = text; }
return { ok: res.ok, status: res.status, body, text };
}
/** Find contact ID by exact email using CRM Search API */
async function findContactIdByEmail(token, email) {
const url = `${HUBSPOT_BASE}/crm/v3/objects/contacts/search`;
const payload = {
filterGroups: [{
filters: [{ propertyName: ‘email’, operator: ‘EQ’, value: email }]
}],
properties: [‘email’],
limit: 1
};
const { ok, status, body, text } = await fetchJson(url, {
method: ‘POST’,
headers: {
Authorization: `Bearer ${token}`,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify(payload),
});
if (!ok) throw new Error(`Search by email failed [${status}]: ${text || ‘’}`);
const id = body?.results?.[0]?.id;
if (!id) throw new Error(`No contact found for email: ${email}`);
return String(id);
}
/** Get primary + additional emails for a contact */
async function getContactEmails(token, contactId) {
const url = `${HUBSPOT_BASE}/crm/v3/objects/contacts/${encodeURIComponent(contactId)}?properties=email,hs_additional_emails&archived=false`;
const { ok, status, body, text } = await fetchJson(url, {
headers: { Authorization: `Bearer ${token}` },
});
if (!ok) throw new Error(`Failed to fetch contact emails [${status}]: ${text || ‘’}`);
const primary = (body?.properties?.email || ‘’).trim();
const rawAdditional = body?.properties?.hs_additional_emails || ‘’;
const additional = rawAdditional
? rawAdditional.split(/[;,\s]+/).map(s => s.trim()).filter(Boolean)
: [];
return { primary, additional };
}
/** Delete a specific additional (secondary) email using legacy endpoint */
async function deleteAdditionalEmail(token, contactId, email) {
const base = `${HUBSPOT_BASE}/contacts/v1/secondary-email/${encodeURIComponent(contactId)}/email/${encodeURIComponent(email)}`;
// Try DELETE first
let { ok, status, text } = await fetchJson(base, {
method: ‘DELETE’,
headers: { Authorization: `Bearer ${token}` },
});
// Fallback to GET for legacy portals that expect it
if (!ok && status === 405) {
const res2 = await fetchJson(base, {
method: ‘GET’,
headers: { Authorization: `Bearer ${token}` },
});
ok = res2.ok; status = res2.status; text = res2.text;
}
if (!ok) throw new Error(`Failed to delete ${email} [${status}]: ${text || ‘’}`);
}
exports.main = async (event, callback) => {
const token =
process.env.ACCESS_TOKEN ||
(event.secrets && event.secrets.ACCESS_TOKEN) ||
‘’;
// Gather potential sources for the contact ID
const fromInput = normalizeId(event.inputFields[‘hs_object_id’]);
const fromEventObj = normalizeId(event.object && (event.object.objectId || event.object.id));
const fromVid = normalizeId(event.inputFields[‘vid’]); // just in case some hubs expose it
// If no ID, try to resolve by email
const emailInput = (event.inputFields[‘email’] || ‘’).trim();
let contactId = fromInput || fromEventObj || fromVid;
// Early diagnostics if token missing
if (!token || !token.trim()) {
return callback({
outputFields: {
attempted_secondary_emails: ‘’,
removed_secondary_emails: ‘’,
removal_errors: ‘No ACCESS_TOKEN secret found. Add a Secret named “ACCESS_TOKEN” and re-save the action.’,
token_diagnostic: ‘token missing’,
id_diagnostic: `inputs: hs_object_id=${fromInput || ‘∅’} event.objectId=${fromEventObj || ‘∅’} vid=${fromVid || ‘∅’} email=${emailInput || ‘∅’}`,
},
});
}
// Resolve ID by email if needed
try {
if (!contactId && emailInput) {
contactId = await findContactIdByEmail(token, emailInput);
}
} catch (e) {
return callback({
outputFields: {
attempted_secondary_emails: ‘’,
removed_secondary_emails: ‘’,
removal_errors: `Could not resolve contact ID. ${String(e)}`,
token_diagnostic: `present ${maskToken(token)}`,
id_diagnostic: `inputs: hs_object_id=${fromInput || ‘∅’} event.objectId=${fromEventObj || ‘∅’} vid=${fromVid || ‘∅’} email=${emailInput || ‘∅’}`,
},
});
}
if (!contactId) {
return callback({
outputFields: {
attempted_secondary_emails: ‘’,
removed_secondary_emails: ‘’,
removal_errors: ‘No contact ID found. Include “hs_object_id” and/or “email” in Properties to include.’,
token_diagnostic: `present ${maskToken(token)}`,
id_diagnostic: `inputs: hs_object_id=${fromInput || ‘∅’} event.objectId=${fromEventObj || ‘∅’} vid=${fromVid || ‘∅’} email=${emailInput || ‘∅’}`,
},
});
}
const mode = (event.inputFields[‘mode’] || ‘remove_all’).trim();
const allowCsv = (event.inputFields[‘allowlist’] || ‘’).toLowerCase();
const allowlist = allowCsv ? allowCsv.split(/[;,]+/).map(s => s.trim()).filter(Boolean) : [];
let attempted = [];
let removed = [];
let errors = [];
try {
const { primary, additional } = await getContactEmails(token, contactId);
let toDelete = mode === ‘keep_allowlist’
? additional.filter(e => !allowlist.includes(e.toLowerCase()))
: additional.slice();
toDelete = toDelete.filter(e => e.toLowerCase() !== (primary || ‘’).toLowerCase());
attempted = toDelete.slice();
for (const e of toDelete) {
try {
await deleteAdditionalEmail(token, contactId, e);
removed.push(e);
await new Promise(r => setTimeout(r, 150));
} catch (err) {
errors.push(`${e}: ${String(err)}`);
}
}
} catch (err) {
errors.push(String(err));
}
return callback({
outputFields: {
attempted_secondary_emails: attempted.join('; ‘),
removed_secondary_emails: removed.join(’; ‘),
removal_errors: errors.join(’ | '),
token_diagnostic: `present ${maskToken(token)}`,
id_diagnostic: `resolved_contact_id=${contactId}`,
},
});
};