This repository contains the official Python client for the OxiMailing API. You don't need to know the API to use it: every route is wrapped in a documented, fully typed method.
OxiMailing lets you send your emails quickly and easily, in the best possible conditions: transactional emails, newsletters and large campaigns, with a strong focus on deliverability. Founded in 2004, we're a small team recognized for the quality of our support and expertise.
To get started, create an account and request your free credits on account.oxemis.com.
- Requirements
- Installation
- Quick start
- Client options
- Error handling
- Objects returned by the API
- Your account
- Senders
- Domains
- Sending emails
- Contact lists
- Unsubscribe lists and bounce list
- Spam complaints
- Tracking: events, statistics, reports
- Tracking accounts
- Callbacks
- History and delivery logs
- Tools
- Cloud
- Pagination
- Testing your code
- Links
- Contribute
- Python 3.10 or higher. The only dependency is httpx.
- An OxiMailing API key (login and password), created in your OxiMailing account.
pip install oximailingStore your API key in environment variables:
export OXIMAILING_API_LOGIN='your API login'
export OXIMAILING_API_PWD='your API password'Then create the client and send your first email:
import os
from oximailing import Message, OxiMailingClient
client = OxiMailingClient(os.environ["OXIMAILING_API_LOGIN"], os.environ["OXIMAILING_API_PWD"])
message = (
Message(
sender="support@example.com", # must be a validated sender (see "Senders")
sender_name="Your company",
subject="Hello world!",
html_message="<p>Hi there! This is my first email sent with the OxiMailing Python client.</p>",
)
.add_recipient_email("joe@example.com")
.add_recipient_email("jane@example.com")
)
sending = client.send_api.send(message)
print("Sending ID:", sending.sending_id)OxiMailing sends 2 emails, one to joe@example.com and one to jane@example.com: Joe doesn't see Jane and vice versa.
The examples below assume client is created as above. The client can also be used as a context manager,
which closes its HTTP connections at the end:
with OxiMailingClient(login, password) as client:
print(client.user_api.get_user().credits)Every option is a keyword argument of the constructor:
client = OxiMailingClient(
login,
password,
timeout=30, # maximum duration of a request, in seconds (default 30)
connect_timeout=10, # maximum duration of the connection (default 10)
max_retries=3, # retries on HTTP 429 "too many requests" (default 3)
user_agent="MyApp/2.1", # appended to the User-Agent header
# base_url="https://api.oximailing.com",
# transport=httpx.MockTransport(handler), # for your tests, see "Testing your code"
# http_client=httpx.Client(proxy="http://proxy.example.com:3128"), # your own httpx client
)The API accepts 10 requests per second per IP address. When it answers HTTP 429, the client waits for the
delay given by the Retry-After header and tries again, up to max_retries times.
All the components share one HTTP client. When you give your own http_client, its timeouts are used and the
client doesn't close it.
Every method raises oximailing.OxiMailingError when the API answers an error, when the network fails, or
when the answer can't be read:
from oximailing import OxiMailingError
try:
client.send_api.send(message)
except OxiMailingError as e:
print(e.code) # HTTP status (400, 401, 403, 404, 406...), 0 for a network error
print(e.message) # message of the API
if e.reason == OxiMailingError.REASON_UNKNOWN_MERGE_FIELDS:
# {{fields}} of the message are missing in the metadata of some recipients
print(e.details) # [{"Field": "FirstName", "MissingFor": 12}, ...]
if e.reason == OxiMailingError.REASON_DATA_QUALITY:
pass # too many invalid or filtered recipients: the sending was refused
if e.is_network_error:
print(e.__cause__) # the original httpx error (DNS, timeout, connection refused...)
# also: e.http_status (None for a network error), e.response_bodyreason is the reason given by the API when there is one, None otherwise (an HTTP error such as a 429
after the retries, or a network error). Errors detected by the library have the code 666 and one of these
reasons:
reason |
When |
|---|---|
OxiMailingError.REASON_INVALID_ARGUMENT |
An argument is invalid (statistics without sending IDs nor dates, a message with both recipients and a list...). |
OxiMailingError.REASON_INVALID_RESPONSE |
The answer of the API is not valid JSON, or not what was expected. |
OxiMailingError.REASON_FILE_NOT_FOUND |
A local file (attachment, upload) doesn't exist. |
OxiMailingError.REASON_INVALID_FILE |
A local file can't be read. |
Only an invalid option of the client raises a standard TypeError.
Methods that perform an action (add, delete, rename, set...) return None and raise OxiMailingError when
they fail. When the API returns something useful (the created list, the uploaded file with its URL, the
counters of an import...), the method returns it.
Answers are returned as immutable, typed dataclasses (User, Sending, ContactList...): use your IDE's
completion, or dataclasses.asdict() to turn them into dicts. Lists of items are tuples.
- Mapping is tolerant: a missing or
nullfield keeps its default value ("",0,None...), unknown fields are ignored. The data received from the API stays available inraw_data. - Instants are timezone-aware
datetimeobjects. Calendar days (validity of the credits, of the subscription...) aredatetime.dateobjects: the day is included. - Dates you pass to the client should be timezone-aware; a naive
datetimeis taken as the local time of your computer.
from oximailing import User
user = client.user_api.get_user()
print("Company:", user.company_name)
print("Credits:", user.credits)
print("Credits valid until (included):", user.credits_valid_before)
print("Subscription:", user.subscription, "emails per month")
print("Used this month:", user.subscription_used_this_month)
print("Daily limit:", user.daily_limit if user.daily_limit is not None else "n/a")
if user.has_feature(User.FEATURE_RECIPIENT_ATTACHMENTS):
print("Recipients may carry their own attachments")
for account in user.tracking_accounts:
print(account.id, account.caption)
if user.scheduled_maintenance_start:
print("Maintenance planned on", user.scheduled_maintenance_start.isoformat())Calendar days (credits_valid_before, subscription_valid_from, subscription_valid_before) are included:
credits valid before 2026-12-31 can be used on December 31.
To send from an address, it must be a validated sender of your account, or belong to an authenticated domain. When you add a sender, a validation email is sent to it: the address stays pending until the link of this email is clicked. Senders can also be managed on this page.
client.senders_api.add_sender("news@example.com", "en") # "en" or "fr": language of the validation email
senders = client.senders_api.get_senders()
print(senders.validated) # ("support@example.com", ...)
print(senders.pending) # ("news@example.com",)
client.senders_api.delete_sender("news@example.com")Authenticate your domains (SPF, DKIM, DMARC) to improve your deliverability, and customize the tracking links with your own domain.
from oximailing import DomainsAPI
client.domains_api.add_domain("example.com")
domain = client.domains_api.get_domain("example.com", DomainsAPI.LANGUAGE_EN)
if domain is not None:
print("Guide:", domain.documentation)
print("SPF:", domain.spf_valid, "DKIM:", domain.dkim_valid, "DMARC:", domain.dmarc_valid)
print(domain.auth_detail) # records to create, expected values, last checks...
# After changing your DNS records
client.domains_api.refresh_domain("example.com")
# Check the SPF records of your domains for OxiMailing
for check in client.domains_api.check_spf():
print(check.domain, check.result, check.detail)
# Tracking links on stats.example.com: create a CNAME stats.example.com pointing to
# domain.auth_detail["TRCK"]["TRCK_dns_redirectto"]. HTTPS is managed by OxiMailing.
client.domains_api.set_tracking_by_dns("example.com", "stats")
# Or with redirection scripts uploaded on your website
client.domains_api.set_tracking_by_files("example.com", "/o.php", "/c.php", "/d.php", https=True, subdomain="www")
# Domains bought through OxiMailing
for reserved in client.domains_api.get_reserved_domains():
print(reserved.domain, "ready" if reserved.ready else "not ready")A Message holds the content, the recipients and the options of a sending; client.send_api.send() sends it.
Every field can be given to the constructor or set later (message.subject = "..."); the add_* methods
return the message, for chaining.
from oximailing import Message
message = (
Message(
sender="support@example.com",
sender_name="Your company",
subject="Your order",
html_message="<p>Thank you for your order.</p>",
txt_message="Thank you for your order.", # optional: generated from the HTML when empty
)
.add_reply_to("contact@example.com")
.add_recipient_email("jane@example.com", "Jane Doe")
.add_cc("sales@example.com") # 3 CC and 3 BCC at most; they get a copy of EVERY email
.add_custom_header("X-Order-Id", "2026-001")
)
sending = client.send_api.send(message)
print("Sending ID:", sending.sending_id)
print(sending.ok_emails) # accepted
print(sending.filtered_emails) # blocked: bounce list, unsubscribe list or red lists
print(sending.invalid_emails) # blocked: invalid addressEach call to send() is followed by a short pause on the API side: put many recipients in one message (or use
send_multiple()) rather than making one call per email.
Every {{Key}} of the subject and the content is replaced by the value of the recipient's metadata (keys are
compared without case):
from oximailing import Message, Recipient
jane = Recipient(
email="jane@example.com",
name="Jane Doe",
meta_data={"FirstName": "Jane", "CustomerId": 1},
token="CUSTOMER-1", # your own reference, echoed back in the events
)
joe = Recipient(email="joe@example.com", meta_data={"FirstName": "Joe", "CustomerId": 2})
message = (
Message(
sender="support@example.com",
subject="Hello {{FirstName}}!",
html_message="<p>Hi {{FirstName}}, your customer ID is {{CustomerId}}.</p>",
)
.add_recipient(jane)
.add_recipient(joe)
)
client.send_api.send(message)If a {{field}} is missing for some recipients, the sending is refused with REASON_UNKNOWN_MERGE_FIELDS
(see Error handling); an empty value is allowed.
from oximailing import Attachment
message.add_attachment("/path/to/terms.pdf") # sent to every recipient
message.add_inline_attachment("/path/to/logo.png", "logo") # <img src="cid:logo"/>
message.html_message = '<p><img src="cid:logo"/></p><p>Hello!</p>'
# From memory (a PDF generated by your program, for example)
message.attachments.append(Attachment.from_content(pdf_bytes, "offer.pdf", "application/pdf"))The MIME type is guessed from the file name when you don't give it (application/octet-stream when unknown).
Files are read when the message is sent.
Each recipient can receive its own files (an invoice, a statement...), in one call for many recipients:
from oximailing import Message, Recipient, User
if not client.user_api.get_user().has_feature(User.FEATURE_RECIPIENT_ATTACHMENTS):
raise RuntimeError("This version of the API doesn't support attachments per recipient.")
message = Message(
sender="billing@example.com",
subject="Your invoice {{InvoiceNumber}}",
html_message="<p>Please find your invoice attached.</p>",
)
for invoice in invoices: # your data
recipient = Recipient(email=invoice["email"], meta_data={"InvoiceNumber": invoice["number"]})
recipient.add_attachment(invoice["pdf_path"], f"invoice-{invoice['number']}.pdf")
message.add_recipient(recipient)
client.send_api.send(message)Each email (message + its recipient's attachments) must stay under the maximum size of a message.
In the HTML of the message:
| Code | Effect |
|---|---|
<a href="#UNSUB#">Unsubscribe</a> |
Unsubscribe link: the recipient is added to the unsubscribe list of the tracking account. |
<a href="#UNSUBALL#">Unsubscribe from everything</a> |
Global unsubscribe link: the recipient is added to the unsubscribe lists of all your tracking accounts. |
<a href="#TRCKCONSENT#">Manage my consent</a> |
Page where the recipient manages its consent to tracking (legal requirement in France since July 2026). |
<a href="https://www.example.com" data-notrack="1"> |
This link is not tracked (kept as is; the attribute is removed). |
These links require tracking: the API enables it when they are present.
Tracking consent. Opens are only measured for recipients who consent to it (GDPR / French CNIL); clicks are always recorded. Give the consent of each named recipient:
recipient.tracking_consent = True # or False; not set: tracked until September 30, 2026, declining afterWhen sending to a contact list, the consent is read from each contact. By default,
#TRCKCONSENT# points to the consent page of the tracking server, and OxiMailing remembers the choice of each
recipient. To use your own page (OxiMailing then relies only on the consent you send):
message.tracking_consent_custom_link = "https://www.example.com/consent?email={{email}}"message.track_emails = True # track opens, clicks, unsubscriptions and bounces
message.tracking_account_id = "ID_OF_ACCOUNT" # tracking account (and its unsubscribe list); default if empty
message.campaign_name = "November newsletter"
message.new_sending = True # new sending ID even within one hour of a sending of the same campaign
message.allow_duplicates = False
# Premium accounts only: send an individual service message (invoice, password reset...) to recipients of
# the unsubscribe list. Never for marketing messages. Bounces and red lists still apply.
message.use_blacklist = FalseBy default, sendings of the same campaign made less than one hour apart share one sending ID: use a distinct
campaign name, or new_sending = True, when you need one ID per call.
message = Message(
sender="news@example.com",
subject="Hello {{FirstName}}",
html_message='<p>Hi {{FirstName}}!</p> <a href="#UNSUB#">Unsubscribe</a>',
track_emails=True,
).set_list(45, "{{FirstName}} {{LastName}}") # list ID, and template of the display name (optional)
client.send_api.send(message)A message is sent either to named recipients or to a list, never both.
from datetime import datetime, timedelta, timezone
# Can I send 5000 emails tomorrow? Nothing is sent nor consumed.
when = datetime.now(timezone.utc) + timedelta(days=1)
check = client.send_api.check_capacity(5000, when)
if not check.can_send:
print("Refused:", check.reason) # CapacityCheck.REASON_NOT_ENOUGH_CREDIT_DAY...
print("Remaining that day:", check.details[0].daily_remaining)
# Several planned sendings, evaluated one after another
check = client.send_api.check_capacities([(600, when), (600, when)])
# Schedule (at least 5 minutes ahead)
message.scheduled_datetime = when
client.send_api.send(message)
for scheduled in client.send_api.get_scheduled():
print(scheduled.sending_id, scheduled.scheduled_datetime, scheduled.subject)
client.send_api.delete_scheduled(123456)
# Several messages in one call: checked together, none is sent if one is refused
results = client.send_api.send_multiple([message1, message2])from oximailing import ListsAPI
contact_list = client.lists_api.create_list("Newsletter", ["FirstName", "LastName"])
result = client.lists_api.add_contacts(
contact_list.id,
{
"jane@example.com": {"FirstName": "Jane", "LastName": "Doe"},
"joe@example.com": {"FirstName": "Joe", "LastName": "Smith"},
},
ListsAPI.MODE_UPDATE, # MODE_IGNORE (default), MODE_INSERT or MODE_UPDATE
)
print(result.added, "added,", result.updated, "updated")
# Also accepted: ["jane@example.com", ...] or [{"email": "jane@example.com", "FirstName": "Jane"}, ...]
for item in client.lists_api.get_lists(with_counts=False): # faster, without counting
print(item.id, item.name, item.extra_fields)
# One page of contacts
page = client.lists_api.get_contacts(contact_list.id, limit=100, offset=0)
print(page.total, "contacts")
for contact in page.contacts:
print(contact["email"])
# Or every contact, page by page
for contact in client.lists_api.iterate_contacts(contact_list.id):
...
client.lists_api.delete_contacts(contact_list.id, ["joe@example.com"])
client.lists_api.rename_list(contact_list.id, "Newsletter 2027")
client.lists_api.delete_list(contact_list.id)Recipients of your unsubscribe lists (one per tracking account) and of your bounce list (invalid
addresses) are filtered out of your sendings. For historical reasons, the unsubscribe lists are handled by
client.blacklists_api (route /blacklists). Addresses are sent in the body of the requests, not in the URL.
# Add or remove addresses (a list, or one string separated by ";")
client.blacklists_api.add_emails(["jane@example.com", "joe@example.com"])
client.blacklists_api.remove_emails("jane@example.com")
client.bounces_api.add_emails(["old@example.com"])
# Read with details (date and source of each unsubscription)
page = client.blacklists_api.get_entries(-1, 5000, details=True)
for entry in page.entries:
print(entry.email, entry.source, entry.date_added)
# Bounce list with the type and the reason of each bounce
for bounce in client.bounces_api.iterate_entries(-1, 5000, details=True):
print(bounce.email, bounce.type, bounce.reason)Incremental synchronisation. Store the sync version and the highest ID you received; next time, download only what changed:
page = client.blacklists_api.get_entries(my_last_id, 5000)
if page.sync_version != my_sync_version:
# addresses were removed since your last synchronisation: download the whole list again
page = client.blacklists_api.get_entries(-1, 5000)
my_sync_version = page.sync_version
my_last_id = page.max_id if page.max_id is not None else my_last_id # continue while pages are full
# With several tracking accounts: the counters of all of them in one call
for info in client.blacklists_api.get_sync_info():
print(info.id, "version", info.sync_version, "last ID", info.last_id)for complaint in client.complaints_api.get_complaints():
print(complaint.email, "via", complaint.complaint_operator)Enable tracking on the message (track_emails=True), then:
from datetime import datetime, timedelta, timezone
from oximailing import Event
# Events of a sending (several types at once)
events = client.tracking_api.get_events([Event.EVENT_TYPE_OPEN, Event.EVENT_TYPE_CLICK], sending_id=sending_id)
for event in events:
print(event.event_type, event.event_email, event.event_info.get("URL", ""))
# Between two dates (no limit on the length; end excluded; start at most 3 years ago)
now = datetime.now(timezone.utc)
events = client.tracking_api.get_events(Event.EVENT_TYPE_UNSUB, start=now - timedelta(days=30), end=now)
# Statistics summed over several sendings, or over a period
stats = client.tracking_api.get_statistics([102639202, 102639203])
if stats is not None:
print(stats.nb_openers, "openers,", stats.nb_clickers, "clickers")
# One entry per sending
by_sending = client.tracking_api.get_statistics_by_sending(start=now - timedelta(days=30))
for s in by_sending.sendings if by_sending else ():
base = s.nb_consenting if s.nb_consenting is not None else s.nb_recipients
print(s.sending_id, s.campaign_name, s.nb_openers, "/", base)
# Report URLs (one per tracking campaign)
for report in client.tracking_api.get_reports([102639202, 102639203], "en"):
print(report.url)The open rate is computed on the recipients who consented to open tracking (nb_consenting, or
nb_recipients when unknown); clicks and unsubscriptions on nb_recipients.
Each tracking account has its own unsubscribe list and records its own events. Most accounts have only one.
for account in client.tracking_accounts_api.get_tracking_accounts():
print(account.id, account.caption)
client.tracking_accounts_api.rename_tracking_account("ID_OF_ACCOUNT", "Brand A") # 25 characters at mostPass the ID as tracking_account_id to the methods of the other components, or to Message.tracking_account_id.
OxiMailing can post the recorded events to a URL of yours. It must answer OK (HTTP 200) when called with
test=1, and when it receives the posted file data.json (same structure as the data part of the events).
client.callbacks_api.set_callback("https://www.example.com/oximailing-callback", 300)
callback = client.callbacks_api.get_callback()
if callback is not None:
print(callback.url, "last OK:", callback.last_ok)
client.callbacks_api.delete_callback()from datetime import datetime, timedelta, timezone
from oximailing import HistoryAPI
# Sendings of your program in the last 30 days (365 days at most)
now = datetime.now(timezone.utc)
sendings = client.history_api.get_sendings(
HistoryAPI.TYPE_ALL, now - timedelta(days=30), now, source=HistoryAPI.SOURCE_API
)
for sending in sendings:
print(sending.sending_id, sending.start_date, sending.subject)
# Technical answers of the server of a recipient (7 days at most; logs must be activated by the support)
for log in client.history_api.get_logs("jane@example.com"):
print(log.date, log.log)# SPF record of any domain
spf = client.tools_api.check_spf("example.com")
print(spf.spf, "=>", spf.result)
# Links of an HTML content
for link in client.tools_api.check_links(html):
if not link.link_accessible:
print("Broken link:", link.link, link.status)Store the images and documents of your messages on the OxiMailing cloud, and use their public URL.
space = client.cloud_api.get_space()
print(space.available, "MB available")
client.cloud_api.create_folder("newsletters", "/")
uploaded = client.cloud_api.upload_file("/path/to/banner.png", "/newsletters", overwrite=True)
print("Public URL:", uploaded.http)
for f in client.cloud_api.list_files("/newsletters", recursive=False):
print(f.name, f.size, "bytes", f.modified_at)
with open("/tmp/banner.png", "wb") as out:
out.write(client.cloud_api.download_file("banner.png", "/newsletters")) # bytes
client.cloud_api.rename_file("banner.png", "banner-2026.png", "/newsletters")
client.cloud_api.delete_file("banner-2026.png", "/newsletters")Campaigns of the OxiMailing software. The cloud also stores the campaigns of the OxiMailing software
(.oximailing files, .emailing for the former software), in their own folders:
for campaign in client.cloud_api.list_campaigns():
print(campaign.path, campaign.name)
client.cloud_api.create_campaign_folder("Archive")
client.cloud_api.move_campaign("offer.oximailing", "/Archive")
content = client.cloud_api.download_campaign("offer.oximailing", "/Archive")| Data | Page | Everything |
|---|---|---|
| Contacts of a list | lists_api.get_contacts(list_id, limit, offset) (total) |
lists_api.iterate_contacts(list_id) |
| Unsubscribe list | blacklists_api.get_entries(last_id, limit) (max_id = next last_id) |
blacklists_api.iterate_entries() |
| Bounce list | bounces_api.get_entries(last_id, limit) |
bounces_api.iterate_entries() |
Give the client an httpx mock transport: no request leaves your computer.
import httpx
from oximailing import OxiMailingClient
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/user"
return httpx.Response(200, json={"CompanyName": "Example", "Credits": 1500})
client = OxiMailingClient("login", "password", transport=httpx.MockTransport(handler))
assert client.user_api.get_user().credits == 1500See CHANGELOG.md for the changes of each version.
Feel free to ask anything, and to contribute to this project:
pip install -e ".[dev]"
pytest # unit tests, without network
mypy --strict src # static analysis
ruff check . # lintNeed help? support@oxemis.com