Secondary email removal

I know this seems to be an ongoing issue that hubspot is yet to sort but has anyone

a) been able to successfully create a way that identifies contact records with more than one email address since secondary email is not a filter?

b) created a workflow or work around that deletes these secondary emails

If anyone can help I’d be hugely greatful :smiling_face:

yes I am aware this setting can be turned off in forms.

yes I am aware removing secondary emails removes anything associated with them.

Hi @squigglebit,

Thank you for reaching out to the Community!

I have a quick solution for your first question: additional email addresses will show as a separate column if you export all of your contacts via the “Actions” button in your contact overview and select the option “Include all email addresses”.

The secodary email addresses will be listed in the column “Additional email addresses” in your export file.

Regarding your second question - I checked our documentation and I believe it’s currently not possible to bulk delete secondary email addresses in HubSpot.

You could delete the email addresses manually by importing a list of contacts that have more than one email address and working through them one by one.

I know this is not ideal if you’re working with a large number of contacts, that’s why I wanted to ask a couple of API experts if they can think of a workaround:

hi @Gonzalo & @lynton, can you think of a way to bulk delete additional email addresses with the help of an API? Thank you!

Cheers
Mia, Community Team

Thank you, any help would be appreciated.
Our CRM holds nearly 600k of contacts, around 18k are affected with secondary emails which isn’t a manual process clean-up friendly number.
I would be interested in any custom code or other ideas that can help with this clean up.

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 <= :smiling_face_with_sunglasses: 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}`,
},
});
};