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", …

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.2.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.2.0
File Size Uploaded Provenance Actions
mailhive-0.2.0.tar.gz 17.6 kB With provenance Details for mailhive-0.2.0.tar.gz

Built distribution (wheel)

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

Total release size: 33.3 kB

Release files / mailhive-0.2.0.tar.gz

Download URL mailhive-0.2.0.tar.gz
Size 17.6 kB
Tags Source
SHA-256 checksum
How to use checksums
cf1b8fc8afaf4857dfc59d1605a5fbc674464a6c2783772a8a9531a0f9b9fe20
BLAKE2b-256 checksum
How to use checksums
0b375837d53e3e2e5d3264df53280dad13b1ca202c41f96ed46963a58988570c
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 Oct 26, 2026.

Transparency log

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

Download URL mailhive-0.2.0-py3-none-any.whl
Size 15.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a9b1ff0797320d9323863ac5bf93bbe97430c7d0696d6a2e3cfadbac29037e1c
BLAKE2b-256 checksum
How to use checksums
c4250d3748120ee25483947afdffa7f7ebbc41532509617fc57cd3415bb46572
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 Oct 26, 2026.

Transparency log

Security for mailhive 0.2.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.2.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 Oct 26, 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