How to extract email addresses from a website in Python

Checked on 2026-11-19.

A company's contact addresses sit in a few predictable places: mailto: links, the text of its contact, about or imprint page, and the footer of the home page. With Requests and Beautiful Soup you can read all of them in about fifty lines of Python. What such a script does not see are addresses a site keeps from scripts on purpose, and pages that are built in the browser.

1. Requests and Beautiful Soup

The plan: fetch the home page, collect addresses from mailto: links and from the visible text, then do the same on the few pages of the site whose address looks like a contact page.

Python
# pip install requests beautifulsoup4
import re
import time
from urllib.parse import unquote, urljoin, urlparse

import requests
from bs4 import BeautifulSoup

EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")
CONTACT_WORDS = ("contact", "about", "imprint", "impressum", "team")
IMAGE_ENDINGS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg")


def read(url, session):
    res = session.get(url, timeout=15)
    res.raise_for_status()
    return res.url, BeautifulSoup(res.text, "html.parser")


def emails_in(soup):
    found = set()
    for link in soup.select('a[href^="mailto:"]'):
        # mailto:one@example.com,two@example.com?subject=Hello
        addresses = unquote(link["href"][len("mailto:"):].split("?")[0])
        found.update(a.strip().lower() for a in addresses.split(",") if "@" in a)
    found.update(match.lower() for match in EMAIL.findall(soup.get_text(" ")))
    return {email for email in found if not email.endswith(IMAGE_ENDINGS)}


def site_emails(domain, max_pages=5):
    session = requests.Session()
    home, soup = read(f"https://{domain}", session)
    emails = emails_in(soup)
    pages = []
    for a in soup.find_all("a", href=True):
        link = urljoin(home, a["href"]).split("#")[0]
        same_site = urlparse(link).hostname == urlparse(home).hostname
        looks_right = any(word in urlparse(link).path.lower() for word in CONTACT_WORDS)
        if same_site and looks_right and link not in pages:
            pages.append(link)
    for link in pages[: max_pages - 1]:
        time.sleep(1)   # one page a second is plenty
        try:
            emails |= emails_in(read(link, session)[1])
        except requests.exceptions.RequestException:
            continue
    return sorted(emails)


print(site_emails("apify.com"))

Three details in it matter. A mailto: link can hold several addresses separated by commas, percent-encoded and followed by ?subject=... (RFC 6068), so it is cut, decoded and split instead of taken whole. The pattern for addresses in text also matches file names such as logo@2x.png, which is why image endings are dropped. And every request has a timeout: the Requests documentation says that without one, requests do not time out.

Keep it polite. Read a handful of pages per site, pause between them, and look at the site's robots.txt first; Python's standard urllib.robotparser reads it.

Where the script stops

  • Addresses hidden from scripts. Cloudflare's Email Address Obfuscation, which Cloudflare says it enables automatically when a site signs up, replaces the addresses in the HTML with [email protected] links and restores them with a script in the visitor's browser. Your script receives the placeholder. Other sites write name [at] example [dot] com or show the address as an image. Each of these is the owner saying no to harvesters, and this guide does not show how to undo them.
  • Pages built in the browser. When the HTML a server sends is a shell that JavaScript fills in, there is no address in it to find. Reading such a page takes a browser automation library such as Playwright, which is slower and heavier than a request.
  • Sites that refuse scripts. Some answer 403 or a challenge page to anything that is not a browser. Then there is nothing to parse.
  • Noise. An address on a page is not always the company's: the agency that built the site, a quoted customer, a placeholder such as name@example.com. Compare each address's domain with the site's.
  • Upkeep. Contact pages are named differently in every language, and the list of words in the script is yours to maintain.

2. An API that returns what a site publishes

The Pipefetch website contacts endpoint is the same job as one HTTPS request. It reads the home page first, then the pages most likely to hold contact details (contact, imprint, about, team), up to the number in pages: 5 by default, 10 at most.

Python
import os
import requests

res = requests.get(
    "https://pipefetch.com/v1/web/contacts",
    params={"url": "apify.com", "pages": 5},   # pages: 1 to 10
    headers={"x-api-key": os.environ["PIPEFETCH_API_KEY"]},
    timeout=90,
)
if res.status_code == 404:
    # no_contacts, website_unreachable or website_blocked: not charged
    print(res.json()["error"]["code"])
else:
    res.raise_for_status()
    data = res.json()["data"]
    print(data["primaryEmail"], data["contactPageUrl"])
    for item in data["emails"]:
        print(item["email"], item["type"], item["mxFound"], item["foundOn"])

Each entry in emails has the address, a type (role for a shared mailbox such as support@), whether it is on the website's own domain (onWebsiteDomain) or at a free mail provider (freeProvider), and the pages it was found on (foundOn). The answer also carries phone numbers, social profiles, the contact page and contact form, and the postal address when the site shows one. The reference lists every field.

Where it stops: in the same place as your script on two counts. It reads pages as plain HTML, so contact details that only appear after a page runs JavaScript are not seen, and a site that refuses automated requests answers 404 website_blocked. Only what the website itself publishes is returned: nothing is guessed, and no other source is asked. What it saves you is the crawling, the filtering and the upkeep, not the limits of the web.

A request costs 1 credit and most take 2 to 9 seconds. A site with no email, phone or social profile on the pages read answers 404 no_contacts, and one that does not answer within about 20 seconds answers 404 website_unreachable; neither costs anything. A new account has 100 free credits and needs no card. This is not an official API of the websites it reads, and Pipefetch is not affiliated with them.

Which one should you use?

SituationUse
A few sites, once, from your own computerThe script
You want full control over which pages are read and how addresses are filteredThe script, extended
A list of company domains, a CRM that fills in contacts as accounts arrive, or code that runs on a serverAn HTTP API such as Pipefetch
A site that hides its addresses from scriptsNeither: use its contact form

Found is not verified

An address on a web page can be years old. Checking that its domain has mail servers catches dead domains, and that is what mxFound in the API's answer tells you. It does not confirm that a mailbox exists: no test message is sent, by the API or by the script above.

What you may do with the addresses

That an address is public does not settle what you may do with it. The European Commission's own examples draw the line: an address such as name.surname@company.com is personal data, an address such as info@company.com is not. The first kind falls under the GDPR for whoever collects and stores it.

Sending is regulated separately. In the United States, the FTC's CAN-SPAM guide says the law "makes no exception for business-to-business email", and its list of practices the law provides criminal penalties for includes "harvesting email addresses".

In practice: prefer the shared mailboxes a company publishes for the purpose, keep only what you need, honor opt-outs, and do not publish or sell lists of people's addresses. Pipefetch's terms forbid using the API to harass people or to send unlawful bulk messages. None of this is legal advice.

Try it with 100 free credits. No card needed. No scraper to build or maintain. Get an API key or read the docs.

Free tools for this

Every source

YouTube

Instagram

TikTok

Facebook

Google

Threads

LinkedIn

App stores

Steam

X

Pinterest

Airbnb

Real estate

Keywords

Job boards

Eventbrite

Shopify stores

Public tenders

All guides