Skip to main content

mailhive

The official Python SDK for Mailhive Send. It supports Python 3.9+, with sync and async clients and a Django email backend.

pip install mailhive

Send an email

from mailhive import Mailhive

client = Mailhive()  # reads MAILHIVE_API_KEY

email = client.emails.send({
    "from": "Acme <hello@acme.com>",
    "to": "ada@example.com",
    "subject": "Your receipt",
    "html": "<p>Thanks for your order.</p>",
})
print(email["id"])

The keys match the API reference exactly: cc, bcc, reply_to, headers, tags, template_id, variables and attachments. You can also pass keyword arguments, with from_ standing in for from:

client.emails.send(from_="hello@acme.com", to="ada@example.com", subject="Hi", text="Hello")

Attachment content can be bytes, which are encoded for you, or base64 text.

client.emails.send_batch([email1, email2])   # up to 100; all accepted or none
client.emails.get(email_id)                  # status: "delivered", "bounced", …

Check addresses before sending

Addresses that can't work — a mistyped domain such as gmial.com, a domain that doesn't exist or has no mail server — are dropped before sending and listed in the result's rejected (address → reason), so they never bounce. To catch them while the person can still fix the typo, run the same checks from your form:

verdicts = client.emails.validate(["ada@gmial.com", "grace@example.com"])
# [{"email": "ada@gmial.com", "valid": False, "reason": "domain_typo", "suggestion": "ada@gmail.com",
#   "message": "The domain looks mistyped.", ...}, {"email": "grace@example.com", "valid": True, ...}]

Up to 100 addresses per call; reason is one of invalid_syntax, domain_typo, domain_not_found, no_mail_server or suppressed. Nothing is sent or stored.

Async

from mailhive import AsyncMailhive

async with AsyncMailhive() as client:
    await client.emails.send({...})

Audiences and contacts

With an API key that has Full access, keep an audience in step with your app or CRM:

contact = client.contacts.upsert(
    audience_id,
    {"email": "ada@example.com", "first_name": "Ada", "fields": {"plan": "pro"}},
)

upsert adds the person, or updates them if they're already there, so it's safe to repeat. Other calls: audiences.list, audiences.create, audiences.rename, contacts.list (pass email= to find one person), contacts.add, contacts.upsert_batch (up to 100; check each result's ok), contacts.get, contacts.update, contacts.unsubscribe and contacts.delete. All of them are on AsyncMailhive too, with await.

Someone who unsubscribed, or reported your email as spam, can't be subscribed again by your code: you get a ConflictError with code contact_unsubscribed. To bring them back, ask them to confirm:

client.contacts.upsert(
    audience_id,
    {
        "email": "ada@example.com",
        "double_opt_in": {"from": "Acme News <news@yourcompany.com>", "subject": "Confirm your subscription"},
    },
)

They're pending, and never mailed by a broadcast, until they click the link. See the contacts API reference.

Retries and idempotency

Every send carries an Idempotency-Key. Retries reuse it, so a retry never sends twice.

  • Retried (up to 2 times, then configurable): network errors, timeouts, 5xx responses, and 429 rate_limited after the Retry-After delay.
  • Not retried: a used-up allowance (monthly_quota_reached, daily_cap_reached) and invalid requests.

To stay safe across restarts, pass your own key:

client.emails.send(email, idempotency_key=f"order-{order.id}-receipt")

Errors

from mailhive import RateLimitError, ValidationError

try:
    client.emails.send(email)
except ValidationError as error:
    print(error.code, error.message, error.details, error.request_id)
except RateLimitError as error:
    if error.code == "monthly_quota_reached":
        ...
Exception Status
AuthenticationError 401
BillingError 402
PermissionDeniedError 403
NotFoundError 404
ConflictError 409 (e.g. idempotency_conflict)
ValidationError 422
RateLimitError 429 (retry_after in seconds)
APIError other statuses, and the base class of all of the above
APIConnectionError no response

All of them subclass MailhiveError.

Webhooks

Pass the raw body, exactly as received:

from mailhive import WebhookVerificationError, verify_webhook

# Django
def mailhive_webhook(request):
    try:
        event = verify_webhook(request.body, request.headers.get("Mailhive-Signature"), settings.MAILHIVE_WEBHOOK_SECRET)
    except WebhookVerificationError:
        return HttpResponse(status=400)
    ...

# Flask: verify_webhook(request.get_data(), request.headers.get("Mailhive-Signature"), secret)
# FastAPI: verify_webhook(await request.body(), request.headers.get("mailhive-signature"), secret)

Django

# settings.py, Django 6.1 and later
MAILERS = {
    "default": {
        "BACKEND": "mailhive.django.EmailBackend",
        "OPTIONS": {"api_key": os.environ["MAILHIVE_API_KEY"]},
    },
}

# settings.py, earlier versions
EMAIL_BACKEND = "mailhive.django.EmailBackend"
MAILHIVE_API_KEY = os.environ["MAILHIVE_API_KEY"]

send_mail, EmailMessage and EmailMultiAlternatives all send through Mailhive, including HTML alternatives, attachments, cc, bcc, Reply-To and extra headers. You can also set message.mailhive_tags or message.mailhive_idempotency_key on a message.

Options

Mailhive(
    api_key="mhs_…",                                 # default: MAILHIVE_API_KEY
    base_url="https://api-beta.mailhive.africa/v1",  # default: MAILHIVE_BASE_URL, then production
    timeout=30.0,
    max_retries=2,
)

Test keys (mhs_test_…) work unchanged: delivery is simulated and nothing is billed. More about test keys.

Metadata

Release files for mailhive 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mailhive 0.3.0
File Size Uploaded Provenance Actions
mailhive-0.3.0.tar.gz 18.9 kB With provenance Details for mailhive-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mailhive 0.3.0
File Interpreter ABI Platform Actions
mailhive-0.3.0-py3-none-any.whl Python 3 none any Details for mailhive-0.3.0-py3-none-any.whl

Total release size: 35.7 kB

Release files / mailhive-0.3.0.tar.gz

Download URL mailhive-0.3.0.tar.gz
Size 18.9 kB
Tags Source
SHA-256 checksum
How to use checksums
52994f13427397ebcf7eb190a2e739789e1d3e93ee64e6cb6c7a9d5e49311687
BLAKE2b-256 checksum
How to use checksums
90f604319717df2074a73ee85b356eedcd3cf3908f1f6d18ef58fefc7809b8fb
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 9, 2026.

Transparency log

Release files / mailhive-0.3.0-py3-none-any.whl

Download URL mailhive-0.3.0-py3-none-any.whl
Size 16.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3904ddd98ce6964dff56f69169425575c5462bfa2679c18ad6c6d7e79e4e646d
BLAKE2b-256 checksum
How to use checksums
507d7422259f77d33acc73558e24467eee39a445be8fad36a709b1935020193d
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 9, 2026.

Transparency log

Security for mailhive 0.3.0

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.

Select from 2 files

Attestation for mailhive-0.3.0.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 9, 2026.

Transparency log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page