Skip to content

About

Official Python library for OxiBounce. Check and validate email addresses, and protect yourself from spamtraps and dangerous addresses.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Official OxiBounce Python Wrapper

MIT License Current Version Python

Overview

This repository contains the official Python wrapper for the OxiBounce API. You don't need to know the API to use it: every route is available as a Python method, and every answer is a typed, immutable object.

OxiBounce verifies email addresses. It checks that an address is well formed and that it really exists, without sending any message. To get started, create an account on account.oxemis.com: free credits are offered when you open it.

Table of contents

Requirements

  • Python 3.10 or higher;
  • httpx (installed automatically, the only dependency).

Installation

pip install oxibounce

Quick start

from oxibounce import OxiBounceClient

with OxiBounceClient("your API login", "your API password") as client:
    # Check one address, waiting at most 10 seconds
    results = client.check_api.check_emails("john.doe@example.com", 10)

    for email, result in results.items():
        print(f"{email}: {result.result} ({result.reason})")

Authentication

Create your API login and password in your account, "OxiBounce" section, "API — For developers" block: "Manage my API keys", then "Create an API key". API access is included in the price: each address checked uses one credit.

We recommend keeping them out of your code, for example in environment variables:

export OXIBOUNCE_API_LOGIN='your API login'
export OXIBOUNCE_API_PWD='your API password'
import os

from oxibounce import OxiBounceClient

client = OxiBounceClient(os.environ["OXIBOUNCE_API_LOGIN"], os.environ["OXIBOUNCE_API_PWD"])

The library sends them in a standard HTTP Basic Authorization header.

Client options

The constructor accepts optional keyword arguments:

client = OxiBounceClient(
    login,
    password,
    timeout=30,  # total timeout of a request, in seconds (default 30)
    connect_timeout=10,  # connection timeout, in seconds (default 10)
    max_retries=3,  # retries on "429 Too Many Requests" (default 3, Retry-After is honoured)
    user_agent="my-app/1.0",  # appended to the User-Agent header
    base_url="https://api.oxibounce.com",  # default
)

A misspelled option raises a TypeError, so a typo does not go unnoticed.

Two options give you control over the HTTP layer:

  • transport: an httpx.BaseTransport, for example an httpx.MockTransport in your tests (see Testing your code);
  • http_client: your own httpx.Client (proxies, certificates, limits…). Its own timeouts apply and the library does not close it. It cannot be combined with transport.

All the components of a client (user_api, check_api, list_api) share one HTTP client. Use the client as a context manager (with OxiBounceClient(...) as client:), or call client.close(), to release the connections.

Every request sends a User-Agent header such as oxibounce-python/1.0.0 (Python 3.12.4), followed by your user_agent suffix.

client.last_response returns the last httpx.Response (status, headers, body), which can help debugging.

Your account

client.user_api.get_user() returns a User object:

Field Content
email Email of the account.
credits Remaining credits (one credit = one address checked).
credits_valid_before Last day of validity of the credits, inclusive, as a datetime.date (Paris time), or None if the account has never received credits. The credits can be used during that whole day and expire the next day.
import os

from oxibounce import OxiBounceClient

with OxiBounceClient(os.environ["OXIBOUNCE_API_LOGIN"], os.environ["OXIBOUNCE_API_PWD"]) as client:
    user = client.user_api.get_user()

    print(f"Account: {user.email}")
    print(f"Remaining credits: {user.credits}")
    if user.credits_valid_before is not None:
        print(f"Credits valid until: {user.credits_valid_before:%Y-%m-%d} (included)")

Checking an email the best way

OxiBounce lets you check addresses in three ways:

  • Synchronously (check_emails()): the best choice to validate an address typed in a form. You set a timeout after which the method returns, so that your users are never blocked. The more time you allow, the better the results.
  • Asynchronously (run_check_async() then get_check_result_async()): the best results, for a background worker for instance. "Async" means that the check runs in the background on the OxiBounce side: these are ordinary Python methods, not coroutines.
  • Lists (list_api): to check a whole file (thousands of addresses or more). This is much more efficient than checking the addresses one by one.

The complete validation of an email address can take time!

Many tests are carried out, some of which depend on the performance of the mail servers of the addresses tested. We always do our best to answer within seconds, but sometimes the whole test takes several minutes.

If you are limited by time, use the synchronous method with an appropriate timeout.

Both check methods accept several addresses, as a string separated by ; or as a list. Batches of any size are supported: the library splits the requests for you (the API accepts 100 test IDs per call). One credit is used per address. The addresses are sent in the body of the request, never in the URL.

Advanced analysis (greylisting). Some servers delay their answer on purpose ("greylisting"). Pass advanced=True to wait for them: the result is more reliable, but the check takes longer (up to several minutes).

Synchronous check

import os

from oxibounce import EmailCheckResult, OxiBounceClient

with OxiBounceClient(os.environ["OXIBOUNCE_API_LOGIN"], os.environ["OXIBOUNCE_API_PWD"]) as client:
    # Second parameter: timeout in seconds (0 = wait until every check is complete).
    # advanced=True: advanced analysis with greylisting (optional, default False).
    results = client.check_api.check_emails("john.doe@example.com;jane.doe@example.com", 10)

    for result in results.values():
        if not result.is_done:
            # The timeout was reached before the end of this check
            print(f"{result.email}: the test is still 'PENDING'.")
        elif result.result == EmailCheckResult.RESULT_OK:
            print(f"{result.email} is valid!")
        elif result.result == EmailCheckResult.RESULT_KO:
            print(f"{result.email} is invalid ({result.reason})!")
        elif result.result == EmailCheckResult.RESULT_NOTSURE:
            # The tests did not reveal whether the address is valid or not.
            # reason and the other fields (is_risky…) help you decide.
            print(f"{result.email} is not sure ({result.reason}).")

The result is a dict indexed by email address.

What to do with "PENDING" checks (timeout reached)?

Short answer: consider them as "NOTSURE".

You can also store their ID (result.id) and get the result later with client.check_api.get_check_result_async_from_id().

Asynchronous check

Step 1: start the checks. Keep the returned list (one EmailCheck per address), or the IDs.

import os
import time

from oxibounce import OxiBounceClient

with OxiBounceClient(os.environ["OXIBOUNCE_API_LOGIN"], os.environ["OXIBOUNCE_API_PWD"]) as client:
    # One address, several addresses separated by ";", or a list of addresses
    tests = client.check_api.run_check_async(["john.doe@example.com", "jane.doe@example.com"])

    for test in tests:
        print(f"{test.email} → test #{test.id}")

    # Step 2: get the status and the results. Ask again until no check is "PENDING".
    # Remember that a check can take minutes.
    while True:
        time.sleep(2)
        results = client.check_api.get_check_result_async(tests)
        if not any(result.is_pending for result in results.values()):
            break

    for result in results.values():
        print(f"{result.email}: {result.result}")

From the IDs only (for instance stored in your database):

results = client.check_api.get_check_result_async_from_id("19211;19212")

get_check_result_async() also accepts IDs: client.check_api.get_check_result_async([19211, 19212]). IDs unknown to the API are ignored: the result is {} when none of them exists.

Understanding the results

result is one of:

Constant Value Meaning
EmailCheckResult.RESULT_OK OK The tests indicate that the address is valid and works.
EmailCheckResult.RESULT_KO KO The address does not work (or no longer works), or it is classified as dangerous.
EmailCheckResult.RESULT_NOTSURE NOTSURE Impossible to know without really sending a message. reason tells why.
EmailCheckResult.RESULT_EMPTY EMPTY Lists only: empty line of the file.
EmailCheckResult.RESULT_CANCELED CANCELED Lists only: the list was stopped before this address was checked.

While a check is PENDING, result is "".

reason gives the detailed code. The most common ones have a constant (EmailCheckResult.REASON_*):

Code Constant Meaning
OK REASON_OK Valid address.
ACCEPT_ALL REASON_ACCEPT_ALL The most common NOTSURE code: the server accepts every address, even invented ones. The address can be used, but only a real sending tells whether it exists.
ERR_GREYLIST REASON_GREYLIST The server uses greylisting; the address is probably good (see the advanced analysis).
ERR_DOESNOTEXIST REASON_DOES_NOT_EXIST The mail server says that the address does not exist.
ERR_NO_MX REASON_NO_MX The domain cannot receive emails.
ERR_INVALID_FORMAT REASON_INVALID_FORMAT Invalid format.
ERR_DISPOSABLE REASON_DISPOSABLE Disposable address.
ERR_DONOTSEND_* REASON_DO_NOT_SEND_PREFIX Dangerous address: do not send to it (result.reason.startswith(EmailCheckResult.REASON_DO_NOT_SEND_PREFIX)).
ERR_TIMEOUT, ERR_CNX, ERR_BL… REASON_TIMEOUT, REASON_CONNECTION, REASON_BL… The server could not be queried: the address could not be judged.

The full list is in our FAQ: OxiBounce return codes.

The other fields of EmailCheckResult:

Field Meaning
domain The domain of the address.
is_format_valid True if the address has a valid format.
is_disposable The address is a disposable address. Disposable addresses can be dangerous because they are not necessarily associated with a single recipient (it is sometimes enough to know the address to read its content). Never send confidential information to such addresses.
is_freemail The address is a "free" address, not associated with a particular company.
is_risky The address or its domain is identified as potentially dangerous. It is strongly recommended not to send to these addresses, to preserve your reputation.
is_robot The address seems to belong to a robot rather than a person or a department. Spamtraps hide behind some of these addresses: be very careful.
is_role The address is that of a department or a generic address (contact@…).
mail_system The email system of the owner of the address, when identified (e.g. "Microsoft").
suggestion For an invalid address, a suggested correction (gmial.com → gmail.com for example). To be used with caution, after a manual validation.
id, email, status ID of the test, address, status (PENDING or DONE); is_done and is_pending test the status.

Every object is a frozen dataclass: dataclasses.asdict(result) turns it into a dict (for JSON, a database…).

Managing lists

Lists are the efficient way to check many addresses: upload a file, start its analysis, follow it, then download the results.

Upload a list. CSV and JSON files are accepted:

  • CSV: one address per line, or several columns separated by ,, ;, tab or |. The column holding the addresses is detected automatically and the header row is optional. Maximum size: 20 MB.
  • JSON: an array of objects having an email property, e.g. [{"name": "Alice", "email": "alice@example.com"}]. Other properties are kept with the address.

The format is detected from the extension (.csv, .json) or from the content.

import os

from oxibounce import OxiBounceClient

with OxiBounceClient(os.environ["OXIBOUNCE_API_LOGIN"], os.environ["OXIBOUNCE_API_PWD"]) as client:
    # Upload a file; the second parameter (optional) names the list
    email_list = client.list_api.add_list("./customers.csv", "Customers 2026")
    print(f"List uploaded as #{email_list.id}")

You can also give the content of the file directly (bytes or str), with a name:

csv = "email\nalice@example.com\nbob@example.com\n"
email_list = client.list_api.add_list(content=csv, name="Customers 2026")

Wait for the import. The list starts with the status IMPORTING, then becomes WAITING (or ERROR if no address was found). Its counters are then available:

import time

from oxibounce import EmailList

list_id = email_list.id
while email_list.status == EmailList.STATUS_IMPORTING:
    time.sleep(2)
    current = client.list_api.get_list(list_id)
    if current is None:  # the list was deleted meanwhile
        raise SystemExit(f"List #{list_id} not found")
    email_list = current

print(
    f"{email_list.nb_emails} lines, {email_list.nb_emails_duplicate} duplicates, "
    f"{email_list.nb_emails_empty} empty, {email_list.nb_emails_invalid_format} invalid formats"
)
print(f"Cost: {email_list.total_cost} credits")

Start the analysis. The credits are used at this step. Like stop_list() and delete_list(), start_list() returns nothing and raises an OxiBounceError when it fails (404 for an unknown list). advanced=True (optional) runs the advanced analysis with greylisting.

client.list_api.start_list(email_list.id)

Follow the analysis. The status becomes PENDING, then DONE:

current = client.list_api.get_list(list_id)
if current is not None:  # None: no list with this ID
    print(f"List is: {current.status}")  # PENDING, DONE, CANCELED…
Status Meaning
EmailList.STATUS_IMPORTING The file is being imported.
EmailList.STATUS_WAITING Ready: call start_list().
EmailList.STATUS_PENDING The analysis is running.
EmailList.STATUS_DONE The analysis is complete.
EmailList.STATUS_CANCELED Stopped by stop_list().
EmailList.STATUS_ERROR The import failed (e.g. no address found in the file).

The dates of a list (created_at, started_at, ended_at) are datetime objects with the time zone given by the API.

Get the results (the list must be DONE or CANCELED). You can keep only one result with the second parameter (RESULT_OK, RESULT_KO or RESULT_NOTSURE):

from oxibounce import EmailCheckResult

for email_check_result in client.list_api.get_list_results(email_list.id):
    print(f"{email_check_result.email}: {email_check_result.result} ({email_check_result.reason})")

# Only the invalid addresses
invalid = client.list_api.get_list_results(email_list.id, EmailCheckResult.RESULT_KO)

Each result is an EmailCheckResult. Its status is DONE for a checked address, or INVALID / EMPTY for a line rejected during the import. Duplicates are not returned.

Stop or delete a list. A list being analysed must be stopped before it can be deleted.

client.list_api.stop_list(email_list.id)
client.list_api.delete_list(email_list.id)

Get all your lists with client.list_api.get_lists() (an empty list if you have none).

Error handling

Every error raises an oxibounce.OxiBounceError:

Attribute Content
code The HTTP status (400, 401, 402, 404…), 0 for a network error, 666 (OxiBounceError.CODE_LIBRARY) for an error detected by the library (file not found, invalid answer, invalid argument).
message The message of the API, e.g. Not enough credit, List already in progress (also str(error)).
reason The Reason sent by the API, when it sends one. For an error detected by the library (code 666): INVALID_ARGUMENT, INVALID_RESPONSE, FILE_NOT_FOUND or INVALID_FILE (constants OxiBounceError.REASON_*). Otherwise None (HTTP error, "429 Too Many Requests" after the retries, network error: see is_network_error).
http_status The HTTP status, or None when there was no answer.
response_body The raw body of the answer, or None.
details Additional details sent by the API, or None.
is_network_error True when the API could not be reached (DNS, timeout, connection refused); the original httpx exception is in __cause__.
import os

from oxibounce import OxiBounceClient, OxiBounceError

with OxiBounceClient(os.environ["OXIBOUNCE_API_LOGIN"], os.environ["OXIBOUNCE_API_PWD"]) as client:
    try:
        client.list_api.start_list(123456)
    except OxiBounceError as e:
        if e.code == 401:
            print("Invalid API login or password")
        elif e.code == 402:
            print("Not enough credits to check this list")
        elif e.code == 404:
            print("Unknown list")
        elif e.is_network_error:
            print(f"The API could not be reached: {e.message}")
        else:
            print(f"Error {e.code}: {e.message}")

When the API answers "429 Too Many Requests", the library waits (as told by the Retry-After header) and tries again, up to max_retries times.

Pagination

No route of the OxiBounce API is paginated: get_lists() and get_list_results() return everything at once. For very large lists, keep in mind that the whole result is loaded in memory.

Testing your code

Give the client an httpx.MockTransport to simulate the API, without any network access:

import httpx

from oxibounce import OxiBounceClient


def fake_api(request: httpx.Request) -> httpx.Response:
    assert request.url.path == "/user"
    return httpx.Response(
        200, json={"Email": "me@example.com", "Credits": 100, "CreditsValidBefore": "2026-12-31"}
    )


client = OxiBounceClient("login", "password", transport=httpx.MockTransport(fake_api))
assert client.user_api.get_user().credits == 100

Links

Contribute / Need help?

Feel free to ask anything, and contribute to this project.

pip install -e ".[dev]"
pytest              # unit tests (no network: the HTTP answers are simulated)
mypy --strict src   # static analysis
ruff check .        # lint

Need help? 👉 support@oxemis.com

About

Official Python library for OxiBounce. Check and validate email addresses, and protect yourself from spamtraps and dangerous addresses.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages