DEV Community

Cover image for A 55-line Python script to find the dead email addresses in your HubSpot export
MailValid.io
MailValid.io

Posted on AI-assisted

A 55-line Python script to find the dead email addresses in your HubSpot export

Someone on the marketing team asks: "How many of our HubSpot contacts are actually reachable?" HubSpot can tell you who has already hard bounced. It can't tell you about the addresses nobody has emailed yet: typos, deleted mailboxes, throwaway signups.

This post is a small Python script that answers that question. It takes a HubSpot contacts export, verifies every address through MailValid's bulk API, and writes a CSV that HubSpot can import back onto the same contacts. Disclosure: I work at MailValid.

Why bother

Two reasons, both from HubSpot's own docs:

  • Billing. Marketing contacts count toward your HubSpot contact tier. Contacts set as non-marketing don't. An address that can't receive mail has no reason to be on your bill.
  • Bounces happen after the fact. HubSpot drops a contact from future marketing emails after it hard bounces. The bounce has already landed on one of your sends by then.

The script gives you a MailValid status on every contact, so you can build a segment of the bad ones and set them as non-marketing.

The flow

HubSpot export (CSV)
  → dedupe the Email column
  → POST /api/v1/verify/bulk   (up to 10,000 per job)
  → poll GET /api/v1/verify/bulk/{job_id}
  → hubspot_import.csv  (Email, MailValid status, MailValid reason)
  → HubSpot import: update existing contacts only
Enter fullscreen mode Exit fullscreen mode

The script

You need Python 3, requests and an API key in MAILVALID_KEY.

import csv, os, sys, time
from collections import Counter
import requests

API = "https://mailvalid.io/api/v1"
HEADERS = {"X-API-Key": os.environ["MAILVALID_KEY"]}
CHUNK = 10_000  # paid plans; the free plan allows 100 emails per job


def call(method, url, **kw):
    """Make a request, waiting out 429s using the Retry-After header."""
    while True:
        r = requests.request(method, url, headers=HEADERS, timeout=30, **kw)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", 10)))
            continue
        r.raise_for_status()
        return r.json()


def read_emails(path):
    with open(path, newline="", encoding="utf-8-sig") as f:
        reader = csv.DictReader(f)
        col = next(c for c in reader.fieldnames if c.strip().lower() == "email")
        seen = {}
        for row in reader:
            email = (row[col] or "").strip()
            if email:
                seen.setdefault(email.lower(), email)
    return list(seen.values())


def verify(emails):
    job = call("POST", f"{API}/verify/bulk", json={"emails": emails})
    while True:
        time.sleep(10)
        state = call("GET", f"{API}/verify/bulk/{job['job_id']}")
        if state["status"] == "completed":
            return state["results"]
        if state["status"] not in ("pending", "processing"):
            sys.exit(f"Job {job['job_id']} ended as {state['status']}")


emails = read_emails(sys.argv[1])
results = []
for i in range(0, len(emails), CHUNK):
    results += verify(emails[i:i + CHUNK])

with open("hubspot_import.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["Email", "MailValid status", "MailValid reason"])
    for r in results:
        w.writerow([r["email"], r["status"], r.get("status_reason", "")])

print(Counter(r["status"] for r in results))
Enter fullscreen mode Exit fullscreen mode

Run it:

export MAILVALID_KEY=mv_live_...
python verify_hubspot.py hubspot-contacts.csv
# Counter({'valid': ..., 'catch_all': ..., 'invalid': ..., ...})
Enter fullscreen mode Exit fullscreen mode

A few notes on the choices:

  • One bulk request per 10,000 emails. Rate limits count verification requests, not emails: 10 per minute on the free plan, 200 on paid. Status polling is a read request with its own, higher limit, so polling every 10 seconds doesn't eat into it. (Rate limits)
  • 429 handling. The API returns 429 Too Many Requests with a Retry-After header. The call() helper just sleeps that long and retries.
  • Dedupe before you send. The script drops repeats, comparing addresses case-insensitively, so you don't verify the same one twice.
  • Credits. The bulk job reserves credits_reserved up front and releases what it doesn't use; the final charge is credits_used. valid, invalid, catch_all and do_not_mail cost one credit each, unknown costs nothing. (Bulk verification)

What the statuses mean for HubSpot

status Meaning In HubSpot
valid Mailbox exists and accepts mail Keep
invalid Can't receive mail Set as non-marketing
do_not_mail May work but risky: disposable, role-based or a past complaint Your call; check status_reason
catch_all Domain accepts everything, mailbox can't be confirmed Keep, but not confirmed
unknown No definite answer Keep, re-run later (free)

status_reason gives the specific cause, for example a disposable domain versus a role address like sales@. The full list is in the status docs.

Getting the results back into HubSpot

  1. In HubSpot, create a custom contact property called MailValid status (a dropdown or single-line text both work), and optionally MailValid reason.
  2. Import hubspot_import.csv and choose to update existing contacts only, so nothing new gets created. HubSpot's import guide lists Email as an identifier it can match contacts on.
  3. Map the two columns to your new properties.
  4. Build a segment where MailValid status is invalid, and set those contacts as non-marketing.

The non-marketing change takes effect on your next HubSpot update date, not immediately, so run this a few days before it.

Where to go from here

The script is a one-off clean-up. For new contacts, a no-code step can verify each one as it's created and write the result to the same property: MailValid has a Zapier action and an Integrately action.

The full non-developer walkthrough, including HubSpot's clean-up tool and the billing timing, is on our blog: How to Clean Invalid Emails Out of HubSpot.

Top comments (0)