This release is a pre-release and may not be stable for production use.
Official Mailjet Python Wrapper
Production-grade, strictly typed Python SDK for the Mailjet Email, Contacts, Statistics, and Content APIs (v3, v3.1, v1, v4). Built on a lightweight __slots__ core with PEP 562 lazy imports for instant cold starts, mailjet-rest combines pooled synchronous Client execution and native HTTP/2 AsyncClient concurrency with full PEP 561 IDE autocompletion across all 89 endpoints, automatic SHA-256 Idempotency-Key fingerprinting, full-jitter retries, TLS 1.2+ and SSRF security guardrails, constant-time webhook signature verification, and a zero-network MockMailjetClient for effortless testing.
Table of contents
- Overview
- Compatibility
- Requirements
- Installation
- Authentication
- Quick Start
- Usage
- Logging & Debugging
- Performance & Architecture
- Security Guardrails
- Request examples
- Deprecation Warnings
- Testing & Webhook Verification
- Type Hinting
- License
- Contribute
- Contributors
Overview
Welcome to the Mailjet official Python API wrapper!
Check out all the resources and Python code examples in the official Mailjet Documentation.
Compatibility
This library mailjet-rest officially supports the following Python versions and platforms (continuously verified in CI across x86_64 and native ARM64 / aarch64):
- Python:
>= 3.10(3.10-3.15) - Platforms & Architectures: Linux (
x86_64,aarch64), macOS (arm64Apple Silicon), and Windows (x86_64and nativewin-arm64/windows-11-arm)
Upcoming Python 3.10 End-of-Support Notice: Because Python 3.10 reaches upstream End-of-Life (EOL) on October 31, 2026,
v1.10.xis the final minor release series withrequires-python = ">=3.10". Support for Python 3.10 will be dropped inv1.11.0(requires-python = ">=3.11").
Requirements
- Build backend:
setuptools,wheel,setuptools-scm - Runtime:
requests >=2.33.0 - Optional async (
mailjet-rest[async]):httpx2 >=2.0.0 - Optional speedups (
mailjet-rest[speedups]):orjson >=3.10.0(fast canonical JSON idempotency fingerprinting)
Test dependencies
For running test you need pytest >=9.0.3 at least.
Make sure to provide the environment variables from Authentication.
Installation
pip install
Create a virtual environment and install the wrapper:
python -m venv venv
source venv/bin/activate
pip install mailjet-rest
# Optional async support (AsyncClient / AsyncEndpoint backed by httpx2>=2.0.0)
pip install "mailjet-rest[async]"
# Optional canonical JSON speedup (orjson>=3.10.0)
pip install "mailjet-rest[speedups]"
git clone & pip install locally
Use the below code to install the wrapper locally by cloning this repository:
git clone https://github.com/mailjet/mailjet-apiv3-python
cd mailjet-apiv3-python
pip install .
conda & make
Use the below code to install it locally by conda and make on Unix platforms:
make install
For development
Using conda
on Linux or macOS:
- A basic environment with a minimum number of dependencies:
make dev
conda activate mailjet
- A full dev environment:
make dev-full
conda activate mailjet-dev
Management script
We provide a universal management script (manage.sh) to simplify local development, testing, and linting.
# 1. Setup the conda environment and pre-commit hooks
./manage.sh env_setup
conda activate mailjet-dev
# 2. Run the test suite, branch coverage gate (>= 93%), mutation tests, and fuzzers
./manage.sh test_all
./manage.sh test_cov
./manage.sh mutation
./manage.sh fuzz_all
# 3. Run the performance profilers
./manage.sh perf_bench
# 4. Format and lint the code
./manage.sh format
./manage.sh lint
Authentication
The Mailjet Email API uses your API and Secret keys for authentication. Grab and save your Mailjet API credentials securely in your environment variables.
export MJ_APIKEY_PUBLIC='your api key' # pragma: allowlist secret
export MJ_APIKEY_PRIVATE='your api secret' # pragma: allowlist secret
export MJ_CONTENT_TOKEN='your_bearer_token' # Optional, for Content API v1
Quick Start
Best Practice: Use the Mailjet Client as a Context Manager (with statement) to automatically pool and close underlying TCP connections, preventing resource leaks.
import os
from mailjet_rest import Client
api_key = os.environ.get("MJ_APIKEY_PUBLIC", "")
api_secret = os.environ.get("MJ_APIKEY_PRIVATE", "")
with Client(auth=(api_key, api_secret), version="v3.1") as mailjet:
data = {
"Messages": [
{
"From": {"Email": "pilot@mailjet.com", "Name": "Mailjet Pilot"},
"To": [{"Email": "passenger1@mailjet.com", "Name": "Passenger 1"}],
"Subject": "Your email flight plan!",
"TextPart": "Welcome to Mailjet! May the delivery force be with you!",
}
]
}
result = mailjet.send.create(data=data)
print(result.status_code)
Warning — Resource Management: If you choose not to use the context manager, you must manually call
mailjet.close()(orawait mailjet.aclose()forAsyncClient) when your application shuts down to release the underlying sockets.
Async Quick Start (mailjet-rest[async])
For asyncio workloads, install pip install "mailjet-rest[async]" (httpx2>=2.0.0) and use AsyncClient with async with:
import asyncio
import os
from mailjet_rest import AsyncClient
async def main() -> None:
auth = (
os.environ.get("MJ_APIKEY_PUBLIC", ""),
os.environ.get("MJ_APIKEY_PRIVATE", ""),
)
async with AsyncClient(auth=auth) as mailjet:
if await mailjet.ping():
# send_v31 is a "v3.1"-pinned shortcut for default version="v3" clients
resp = await mailjet.send_v31.create(
data={
"Messages": [
{
"From": {
"Email": "pilot@mailjet.com",
"Name": "Mailjet Pilot",
},
"To": [
{
"Email": "passenger1@mailjet.com",
"Name": "Passenger 1",
}
],
"Subject": "Async email flight plan!",
"TextPart": "Hello from AsyncClient!",
}
]
}
)
print(resp.status_code)
asyncio.run(main())
See samples/async_client_sample.py for ping(), update(), available_endpoints, and async for ... in client.contact.stream() pagination.
Advanced Configuration
You can pass configuration overrides directly when initializing the Client (or via a Config object) and during individual API calls:
from mailjet_rest import Client, Config
cfg = Config(
version="v3.1",
api_url="https://api.us.mailjet.com/",
timeout=30,
max_retries=3, # 0..20 transient retries with full jitter
auto_idempotency_mode="fingerprint", # "fingerprint" | "uuid4" | "off"
pool_connections=100,
pool_maxsize=100,
verify=True, # or path to a custom CA bundle file
trust_env=False, # set True to honor ambient HTTPS_PROXY / REQUESTS_CA_BUNDLE / ~/.netrc
warn_unclosed=False, # opt-in ResourceWarning on unclosed Client/AsyncClient
)
with Client(auth=(api_key, api_secret), config=cfg) as mailjet:
# Override timeout for a single, heavy request
result = mailjet.contact.get(timeout=60)
API Versioning
The Mailjet API is spread among distinct versions:
v3- The Email APIv3.1- Email Send API v3.1, which is the latest version of our Send APIv1- Content API (Templates, Blocks, Images)v4- GDPR Contact Erasure API (client.contacts.delete(id=...))
Since most Email API endpoints are located under v3, it is set as the default one and does not need to be specified when making your request.
For the others you need to specify the version using version. For example, if using Send API v3.1:
with Client(
auth=(api_key, api_secret),
version="v3.1",
) as mailjet:
pass # Your requests here
Alternatively, on a default version="v3" Client or AsyncClient, client.send_v31 (POST /v3.1/send) acts as a "v3.1"-pinned shortcut so /v3/REST/* endpoints and Send API v3.1 calls can share a single client instance and connection pool.
For additional information refer to our API Reference.
Base URL
The default base domain name for the Mailjet API is api.mailjet.com. You can modify this base URL by setting a value for api_url in your call:
with Client(
auth=(api_key, api_secret),
api_url="https://api.us.mailjet.com/",
) as mailjet:
pass # Your requests here
If your account has been moved to Mailjet's US architecture, the URL value you need to set is https://api.us.mailjet.com.
Usage
Error Handling
The client raises typed exceptions inheriting from ApiError for both network failures and HTTP 4xx/5xx error responses (ValidationError on 400, MailjetAuthError on 401/403, DoesNotExistError on 404, ApiRateLimitError on 429, MailjetApiError on other HTTP errors, and TimeoutError / CriticalApiError on transport failures).
from mailjet_rest import (
ApiError,
CriticalApiError,
MailjetAuthError,
TimeoutError,
ValidationError,
)
try:
result = mailjet.contact.get()
print(result.json())
except TimeoutError:
print("The request to the Mailjet API timed out.")
except CriticalApiError as e:
print(f"Network connection failed: {e}")
except MailjetAuthError as e:
print(f"Authentication failed ({e.status_code}): {e}")
except ValidationError as e:
print(f"Validation error ({e.status_code}): {e}")
except ApiError as e:
print(f"API error: {e}")
Logging & Debugging
The SDK integrates seamlessly with Python's standard logging library and features Smart Telemetry.
If you pass identifiers like CustomID, Campaign, or TemplateID in your payload, the SDK automatically extracts them and injects a Trace context into your logs.
This allows you to easily correlate local application errors with your Mailjet Dashboard analytics.
import logging
from mailjet_rest import Client
logging.getLogger("mailjet_rest.client").setLevel(logging.DEBUG)
logging.basicConfig(format="%(levelname)s - %(message)s")
with Client(auth=(api_key, api_secret), version="v3.1") as mailjet:
# Adding 'CustomID' enables Smart Tracing in the console logs
mailjet.send.create(
data={
"Messages": [
{
"From": {"Email": "test@test.com"},
"To": [{"Email": "user@test.com"}],
"CustomID": "Promo_Black_Friday",
}
]
}
)
Console output will feature: DEBUG - Sending Request: POST ... | Trace: [CustomID=Promo_Black_Friday]
IDE Autocompletion & DX
Because the SDK utilizes dynamic URL dispatching (__getattr__), to prevent "Magic Method Traps" (accidentally dispatching internal Python methods), the SDK includes strict poka-yoke guardrails.
Attempting to access private attributes or removed properties (like client.auth) will safely throw an explicit AttributeError instead of a ghost API request, and misspelled endpoints emit difflib "Did you mean '...'?" suggestions.
You can also inspect client.available_endpoints for runtime route discovery and call client.ping() (or await async_client.ping()) for lightweight API health/credential checks.
URL path
According to python special characters limitations we can't use slashes / and dashes - which is acceptable for URL path building. Instead, python client uses another way for path building. You should replace slashes / by underscore _ and dashes - by capitalizing next letter in path.
For example, to reach statistics/link-click path you should call statistics_linkClick attribute of python client.
# GET `statistics/link-click`
with Client(auth=(api_key, api_secret)) as mailjet:
filters = {"CampaignId": "xxxxxxx"}
result = mailjet.statistics_linkClick.get(filters=filters)
print(result.status_code)
print(result.json())
For the Content API (v1), sub-actions will be correctly routed using slashes (e.g. contents/lock). Additionally, the SDK maps the data_images resource specifically to /v1/data/images to support media uploads.
# GET '/v1/data/images'
with Client(auth=(api_key, api_secret), version="v1") as mailjet:
result = mailjet.data_images.get()
Strict Payload Builders
Tired of getting 400 Bad Request because of a typo in your JSON payload? Import our TypedDict schemas to get full IDE autocomplete and static type checking.
from mailjet_rest.types import SendV31Payload, SendV31Message
message: SendV31Message = {
"From": {"Email": "pilot@mailjet.com", "Name": "Mailjet Pilot"},
"To": [{"Email": "passenger1@mailjet.com", "Name": "passenger 1"}],
"Subject": "Your flight plan!",
"TextPart": "Dear passenger, welcome to Mailjet!",
}
payload: SendV31Payload = {"Messages": [message]}
mailjet.send.create(data=payload)
Performance & Architecture
The Mailjet SDK v1.6.0+ has been heavily optimized for high-concurrency and memory-constrained environments (like AWS Lambda).
It utilizes __slots__ for memory density, immutable MappingProxyType headers for zero-allocation merging, and O(1) dynamic endpoint caching.
For a detailed breakdown of our nanosecond routing benchmarks and instructions on how to profile the SDK, please read our Performance & Architecture Guide.
Security Guardrails
The SDK includes active protections against common API vulnerabilities based on Defense-in-Depth principles:
Additional built-in protections:
- SSRF & Open Redirects: Hard-disabled automatic redirects and enforced strict hostname validation.
- CRLF Injection: Native string evaluation blocks header injection attempts via compromised Bearer tokens or custom headers.
- Downgrade Attacks: Enforced TLS 1.2+ minimum version via a custom
SecureHTTPAdapter. - Idempotency Fingerprinting: Automatically generates SHA-256
Idempotency-Keyheaders for mutating requests (POST,PUT, andDELETE), configurable viaConfig.auto_idempotency_mode("fingerprint","uuid4", or"off"). - SpamGuard Analysis: Pre-flight HTML static analyzer that intercepts and blocks XSS vectors (e.g.,
<script>,onerror=) before network dispatch. - Secret Obfuscation (CWE-316): Utilizes a custom
SecretAuthtransport adapter andRedactingFilterto strictly prevent API credentials from leaking in tracebacks, logs, or memory dumps. - Punycode IDN Support: Automatically normalizes Internationalized Domain Names (IDNs) in sender and recipient addresses to prevent Homograph attacks.
See our SECURITY.md for our vulnerability disclosure policy and supported versions.
Local-First Validation (Fail-Fast)
Instead of waiting for server-side roundtrips, the SDK promotes "Parse, Don't Validate" at the boundary. By using strictly typed models (like SendV31Payload), any attempt at Mass Assignment (BOPLA) or sending invalid data formats is caught locally in microseconds.
(See the Strict Payload Builders section for examples).
Runtime Security (PEP 578)
For Enterprise and SecOps environments, the SDK acts as a security sensor. It emits native Python audit events (sys.audit) for all outbound network egress and explicit TLS bypass attempts.
You can opt-in to have the SDK automatically listen to these events and pipe them to your logging infrastructure for SIEM integration:
from mailjet_rest import Client, Config
# Activate the PEP 578 Audit Listener
cfg = Config(enable_security_audit=True)
with Client(auth=(api_key, api_secret), config=cfg) as mailjet:
pass # Your secure requests here
Network Resilience & Retries
The SDK incorporates a custom JitterRetry connection pooling policy to gracefully handle transient network drops, 5xx server errors, and 429 Too Many Requests limits. It utilizes exponential backoff combined with randomized full jitter to prevent the "Thundering Herd" effect on Mailjet's upstream API during concurrent high-throughput batching.
While the SDK automatically configures resilient retries natively, you can tune the retry budget via Config(max_retries=5) or subclass/mount SecureHTTPAdapter (never raw HTTPAdapter, which would strip TLS 1.2+ pinning and CA trust-store isolation):
import os
import random
from urllib3.util.retry import Retry
from mailjet_rest import Client, Config
from mailjet_rest.utils.guardrails import SecureHTTPAdapter
class CustomJitterRetry(Retry):
"""Stateless RetryPolicy with Full Jitter to prevent the Thundering Herd."""
def get_backoff_time(self) -> float:
backoff = super().get_backoff_time()
# Apply full jitter: randomly scale the backoff
return random.uniform(0, backoff) if backoff > 0 else 0
# 1. Recommended: tune transient retry budget directly via Config
with Client(auth=(api_key, api_secret), config=Config(max_retries=5)) as mailjet:
result = mailjet.contact.get()
# 2. Advanced: mount SecureHTTPAdapter with a custom Retry policy (preserves TLS 1.2+ pinning)
custom_retry_strategy = CustomJitterRetry(
total=5,
backoff_factor=0.5,
status_forcelist=[429, 500, 502, 503, 504],
raise_on_status=False, # Let the client parse 429/500 into custom Mailjet exceptions
)
api_key = os.environ.get("MJ_APIKEY_PUBLIC", "")
api_secret = os.environ.get("MJ_APIKEY_PRIVATE", "")
with Client(auth=(api_key, api_secret)) as mailjet:
# Always use SecureHTTPAdapter so TLS 1.2+ and isolated CA verification remain enforced
adapter = SecureHTTPAdapter(max_retries=custom_retry_strategy)
mailjet.session.mount("https://", adapter)
# Subsequent API calls will utilize your custom retry engine
result = mailjet.contact.get()
Request examples
Full list of supported endpoints
Important: Full runnable code examples for every supported endpoint are available in
samples/.
Executable README (Smoke Test)
Want to test all these examples at once? We provide an executable script that dynamically creates, tests, and safely cleans up all resources mentioned in this document. It's a great way to verify your API credentials and network access.
Simply run:
python samples/smoke_readme_runner.py
Send API (v3.1)
Send a basic email
from mailjet_rest import Client
import os
api_key = os.environ.get("MJ_APIKEY_PUBLIC", "")
api_secret = os.environ.get("MJ_APIKEY_PRIVATE", "")
data = {
"Messages": [
{
"From": {"Email": "pilot@mailjet.com", "Name": "Mailjet Pilot"},
"To": [{"Email": "passenger1@mailjet.com", "Name": "Passenger 1"}],
"Subject": "Your email flight plan!",
"TextPart": "Dear passenger 1, welcome to Mailjet!",
"HTMLPart": "<h3>Dear passenger 1, welcome to Mailjet!</h3>",
}
]
}
with Client(auth=(api_key, api_secret), version="v3.1") as mailjet:
result = mailjet.send.create(data=data)
print(result.status_code)
print(result.json())
Send an email using a Mailjet Template
When using TemplateLanguage, ensure that you pass a standard Python dictionary to the Variables parameter.
data = {
"Messages": [
{
"From": {"Email": "pilot@mailjet.com", "Name": "Mailjet Pilot"},
"To": [{"Email": "passenger1@mailjet.com", "Name": "passenger 1"}],
"TemplateID": 1234567, # Put your actual Template ID here
"TemplateLanguage": True,
"Subject": "Your email flight plan!",
"Variables": {"name": "John Doe", "custom_data": "Welcome aboard!"},
}
]
}
with Client(auth=(api_key, api_secret), version="v3.1") as mailjet:
result = mailjet.send.create(data=data)
Building Complex Payloads (MessageBuilder & SendPayloadBuilder)
For complex scenarios like Send API v3.1, manually constructing nested dictionaries is error-prone.
The MessageBuilder provides a fluent interface that handles structure, attachment encoding, and validation automatically.
import os
from mailjet_rest import Client
from mailjet_rest.builders import MessageBuilder, SendPayloadBuilder
api_key = os.environ.get("MJ_APIKEY_PUBLIC", "")
api_secret = os.environ.get("MJ_APIKEY_PRIVATE", "")
# Fluently construct an email
message = (
MessageBuilder()
.set_sender("pilot@mailjet.com", "Mailjet Pilot")
.add_recipient("passenger@mailjet.com", "John Doe")
.add_cc("copilot@mailjet.com")
.set_subject("Your Boarding Pass")
.set_content(html="<h3>Welcome aboard!</h3>")
.set_custom_id("boarding-pass-001")
.set_tracking(opens="enabled", clicks="enabled")
.set_list_unsubscribe("https://example.com/unsubscribe", "unsubscribe@example.com") # RFC 8058
# Safely encodes using memory-efficient ChunkedStreamer
.attach_file("tickets/pass.pdf")
.attach_inline("assets/logo.png", content_id="logo") # Adds inline CID attachments safely
.build()
)
# Safely wrap the message using the root payload builder
payload = SendPayloadBuilder().add_message(message).set_sandbox_mode(True).build()
# Send via client
with Client(auth=(api_key, api_secret), version="v3.1") as mailjet:
result = mailjet.send.create(data=payload)
print(result.status_code)
print(result.json())
Standard REST Actions (GET, POST, PUT, DELETE)
Note: All examples in this section assume that you have already opened a session using the context manager, for example:
with Client(auth=(api_key, api_secret)) as mailjet:.
POST (Create)
Simple POST request
# Create a new contact
data = {"Email": "Mister@mailjet.com"}
result = mailjet.contact.create(data=data)
print(result.json())
The support for explicit per-request custom HTTP headers (e.g. tracking or custom metadata) across create(), update(), and direct endpoint calls.
# Pass custom per-request headers (screened for CRLF safety)
result = mailjet.contact.create(
data={"Email": "pilot@mailjet.com"},
headers={"X-Custom-Source": "Onboarding-Service"},
)
Using actions
# Manage the subscription status of a contact to multiple lists
id_ = "$ID"
data = {
"ContactsLists": [
{"ListID": "$ListID_1", "Action": "addnoforce"},
{"ListID": "$ListID_2", "Action": "addforce"},
]
}
result = mailjet.contact_managecontactslists.create(id=id_, data=data)
print(result.json())
Zero-Leak Sandbox Mode (dry_run)
Developing locally? Stop accidentally sending emails to real users.
Enable dry_run=True to safely intercept all network mutations (POST, PUT, DELETE).
# Intercepts state-changing requests and injects SandboxMode where applicable
with Client(auth=(api_key, api_secret), dry_run=True) as dry_run_client:
# This will NOT hit the actual database, returning a mock 200 OK safely
dry_run_client.contact.create(data={"Email": "real_user@example.com"})
GET Request
Retrieve all objects
# Retrieve all contacts
result = mailjet.contact.get()
print(result.json())
GET (Read one)
# Retrieve a specific contact ID
id_ = "Contact_ID"
result = mailjet.contact.get(id=id_)
print(result.json())
Using filtering
# Retrieve contacts that are not in the campaign exclusion list
filters = {
"limit": 40,
"offset": 50,
"sort": "Email desc",
"IsExcludedFromCampaigns": "false",
}
result = mailjet.contact.get(filters=filters)
print(result.json())
Using pagination
Some requests (for example GET /contact) has limit, offset and sort query string parameters. These parameters could be used for pagination.
limit int Limit the response to a select number of returned objects. Default value: 10. Maximum value: 1000
offset int Retrieve a list of objects starting from a certain offset. Combine this query parameter with limit to retrieve a specific section of the list of objects. Default value: 0
sort str Sort the results by a property and select ascending (ASC) or descending (DESC) order. The default order is ascending. Keep in mind that this is not available for all properties. Default value: ID asc
Next example returns 40 contacts starting from 51st record sorted by Email field descendally:
filters = {
"limit": 40,
"offset": 50,
"sort": "Email desc",
}
result = mailjet.contact.get(filters=filters)
print(result.json())
Lazy Pagination (The .stream() method)
Stop writing while loops to fetch thousands of contacts. Use .stream() to return a native Python Generator. The SDK will automatically manage Limit, Offset, and network pagination under the hood.
Streaming continues until a short or empty page is returned. It does not use Total as the collection size, since normal REST responses report the number of elements in the current page.
# -------------------------------------------------------------
# 1. Manual Single-Page Query (GET)
# Best when building custom paginated UI tables (e.g., page 5)
# -------------------------------------------------------------
page_filters = {
"Limit": 50, # Max 1000 per Mailjet API specification
"Offset": 100, # Skips first 100 records
"Sort": "ID ASC",
}
response = mailjet.contact.get(filters=page_filters)
contacts_page = response.json().get("Data", [])
print(f"Retrieved {len(contacts_page)} contacts on this page.")
# -------------------------------------------------------------
# 2. Lazy Auto-Streaming (stream)
# Best for processing large datasets without loading everything into RAM
# -------------------------------------------------------------
# Automatically increments Offset and requests pages in chunks of 500
for contact in mailjet.contact.stream(chunk_size=500):
print(contact["Email"])
Resuming Streams and Query Parsing from an existing offset or raw query parameters
from urllib.parse import parse_qs
# Resuming a stream from a saved progress checkpoint:
# Begins fetching from record 1000 onwards in chunks of 250
for contact in mailjet.contact.stream(filters={"Offset": 1000}, chunk_size=250):
process_contact(contact)
# Consuming parsed URL query parameters directly:
# Normalizes list values like {"offset": ["500"]} safely
query_params = parse_qs("offset=500&sort=Email+desc")
for contact in mailjet.contact.stream(filters=query_params, chunk_size=100):
print(contact["Email"])
PUT (Update / Patch specific fields)
A PUT request in the Mailjet API will work as a PATCH request - the update will affect only the specified properties. The other properties of an existing resource will neither be modified, nor deleted. It also means that all non-mandatory properties can be omitted from your payload.
# Update the contact properties for a contact
id_ = "$CONTACT_ID"
data = {
"Data": [
{"Name": "first_name", "value": "John"},
{"Name": "last_name", "value": "Smith"},
]
}
result = mailjet.contactdata.update(id=id_, data=data)
print(result.json())
DELETE (Returns 204 No Content)
Upon a successful DELETE request the response will not include a response body, but only a 204 No Content response code.
# Delete an email template (v3)
id_ = "Template_ID"
result = mailjet.template.delete(id=id_)
print(result.status_code)
# Permanently erase a contact (v4 GDPR)
result = mailjet.contacts.delete(id=contact_id)
print(result.status_code)
Email API Ecosystem (Webhooks, Parse API, Segmentation, Stats)
Webhooks (Real-time Event Tracking)
You can subscribe to real-time events (open, click, bounce, etc.) by configuring a webhook URL using the eventcallbackurl resource.
data = {
"EventType": "open",
"Url": "https://www.mydomain.com/webhook",
"Status": "alive",
}
result = client.eventcallbackurl.create(data=data)
Parse API (Receive Inbound Emails)
The Parse API routes incoming emails sent to a specific domain to your custom webhook.
data = {"Url": "https://www.mydomain.com/mj_parse.php"}
result = client.parseroute.create(data=data)
Segmentation (Contact Filters)
Create expressions to dynamically filter your contacts (e.g., customers under 35) using contactfilter.
data = {
"Description": "Will send only to contacts under 35 years of age.",
"Expression": "(age<35)",
"Name": "Customers under 35",
}
result = client.contactfilter.create(data=data)
Retrieve Campaign Statistics
Retrieve performance counters using statcounters or location-based statistics via geostatistics.
from mailjet_rest import Client
import os
auth = (
os.environ.get("MJ_APIKEY_PUBLIC", ""),
os.environ.get("MJ_APIKEY_PRIVATE", ""),
)
with Client(auth=auth) as mailjet:
filters = {
"CounterSource": "APIKey",
"CounterTiming": "Message",
"CounterResolution": "Lifetime",
}
# Getting general statistics
result = mailjet.statcounters.get(filters=filters)
print(result.status_code)
print(result.json())
Content API
Requires version="v1". You can authenticate using Basic Auth or a Bearer Token.
The Content API (v1) allows managing templates, generating API tokens, and uploading images. The SDK handles the required /REST/ prefix for most resources automatically, while appropriately mapping data_images to /data/.
Generating a Token
# Tokens endpoint requires Basic Auth initially
with Client(auth=(api_key, api_secret), version="v1") as client:
data = {
"Name": "My Access Token",
"Permissions": ["read_template", "create_template"],
}
result = client.tokens.create(data=data)
print(result.json())
Uploading an Image via Multipart Form-Data
To upload physical files, use the data_images resource and delete the default Content-Type header so requests can generate proper multipart boundaries. The request will be mapped to /v1/data/images.
import base64
# Base64 encoded image data (1x1 transparent PNG)
b64_string = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
image_bytes = base64.b64decode(b64_string)
# The Image upload requires a JSON metadata part (with a Status) and the physical file part
files_payload = {
"metadata": (None, '{"name": "logo.png", "Status": "open"}', "application/json"),
"file": ("logo.png", image_bytes, "image/png"),
}
# Deleting the default Content-Type header allows requests to generate multipart/form-data
result = client.data_images.create(headers={"Content-Type": None}, files=files_payload)
Locking a Template Content
Sub-actions are safely handled using slashes (e.g., template_contents_lock becomes templates/<template_id>/contents/lock).
template_id = 1234567
# This routes to POST /v1/REST/templates/1234567/contents/lock
result = client.template_contents_lock.create(id=template_id)
Deprecation Warnings
The SDK includes an active native Python deprecation system to protect your application from sudden API breaking changes.
If you attempt to use legacy arguments (like ensure_ascii or data_encoding), obsolete utility functions (parse_response), or ambiguous routing (v1 with /template), the SDK will not break your code.
It will successfully execute the request but will emit a non-breaking DeprecationWarning to help you gracefully migrate to modern standards.
Deprecated API Endpoints & Routes
When calling retired Mailjet endpoints, the SDK executes the request but emits an actionable DeprecationWarning directing you to canonical replacements:
- Newsletters (
newsletter*): Migrate tocampaigndraftandcampaigndraft_*. - Legacy Statistics (
campaignstatistics,messagesentstatistics,liststatistics,domainstatistics,apikeytotals): Migrate tostatcountersorstatistics_recipientEsp. - Webhook Alias (
client.webhook): Use the official REST resourceclient.eventcallbackurl. - Ambiguous Templates (
templates_contents): Usetemplate_detailcontent(v3) ortemplate_contents(v1).
Testing & Webhook Verification
Eliminate HTTP mocking boilerplate in unit tests using MockMailjetClient (note: because Client and AsyncClient use strict __slots__, patch methods at the class level via unittest.mock.patch.object(Client, "api_call", ...) rather than assigning client.api_call = ... on an instance), and validate inbound webhook callbacks in constant time with replay-window enforcement:
from mailjet_rest import MockMailjetClient, verify_webhook_signature
with MockMailjetClient() as mock_client:
res = mock_client.send_v31.create(data={"Messages": [{"Subject": "Hi"}]})
assert res.status_code == 200
assert len(mock_client.sent_requests) == 1
is_valid = verify_webhook_signature(
payload_bytes=raw_body,
signature_header=request_sig,
webhook_secret=signing_secret,
timestamp_unix=event_ts,
max_age_seconds=300,
)
Type Hinting
This SDK ships PEP 561 py.typed metadata with inline PEP 484 annotations and hover docstrings across all 20 modules, deterministic .pyi stubs only for dynamic __getattr__ route dispatch (mailjet_rest/client.pyi and mailjet_rest/endpoint.pyi), and consolidated TypedDict DTOs in mailjet_rest.types (e.g., SendV31Payload, SendV31Response, ContactPayload, V1TemplatePayload). Static type checkers (mypy --strict, pyright) and IDEs get full autocompletion for all 89 registered routes on both Client and AsyncClient, plus client.available_endpoints for runtime discovery.
License
Contribute
Mailjet loves developers. You can be part of this project!
This wrapper is a great introduction to the open source world, check out the code!
Feel free to ask anything, and contribute:
- Fork the project.
- Create a new branch.
- Implement your feature or bug fix.
- Add documentation to it.
- Commit, push, open a pull request and voilà.
If you have suggestions on how to improve the guides, please submit an issue in our Official API Documentation repo.
Contributors
Metadata
Release files for mailjet-rest 1.10.0rc2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| mailjet_rest-1.10.0rc2.tar.gz | 129.0 kB | With provenance | Details for mailjet_rest-1.10.0rc2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| mailjet_rest-1.10.0rc2-py3-none-any.whl | Python 3 | none | any | Details for mailjet_rest-1.10.0rc2-py3-none-any.whl |
Total release size: 214.1 kB
Release files / mailjet_rest-1.10.0rc2.tar.gz
| Download URL | mailjet_rest-1.10.0rc2.tar.gz |
|---|---|
| Size | 129.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e945ff31eb3e17666423573d988da9aeb2c81ca2e5374f7ae22b6fa9b1113402
|
|
BLAKE2b-256 checksum How to use checksums |
697226c53ff5fa3d7678fba5de24475c10c0ac6727e26e26d57de82569aaaa63
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logRelease files / mailjet_rest-1.10.0rc2-py3-none-any.whl
| Download URL | mailjet_rest-1.10.0rc2-py3-none-any.whl |
|---|---|
| Size | 85.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cc432bf8098ebd5bae39be15e9f54851e455198f0d37dccbccc3121d84dd6682
|
|
BLAKE2b-256 checksum How to use checksums |
9580e44a5ccb7c1588744eaf8060ec5ac97741f9d4c260d97b2869344ca668e0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logSecurity for mailjet-rest 1.10.0rc2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for mailjet_rest-1.10.0rc2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.