Mailgent Python SDK
The official Python SDK for the Mailgent API -- identity, mail, vault, calendar, and Mailgent Pay for AI agents.
Installation
pip install mailgent-sdk
The distribution is
mailgent-sdkon PyPI, but the import name ismailgent.
Buyer payments (x402)
Pay any x402-protected URL from your project's wallet. Mailgent drives the full handshake — discover the 402 challenge, enforce mandate caps, sign EIP-3009, retry, and record — then returns a discriminated result.
result = client.payments.pay(url="https://api.example.com")
if result["ok"]:
print(result["txHash"], result["cost"]["amountUsdc"])
else:
print(result["code"], result["hint"])
Spend policy lives at client.payments.mandates. Requires the
payments:spend scope on the API key. See the
full payments guide.
Webhook signature verification
Mailgent sends X-Mailgent-Signature: sha256=<hex> (HMAC-SHA256 of the raw
request body) along with X-Mailgent-Event / X-Mailgent-Idempotency-Key.
The signing secret is generated by Mailgent when you register an endpoint
in the Console and shown to you exactly once.
import os
from fastapi import FastAPI, HTTPException, Request
from mailgent.webhook import verify_webhook
app = FastAPI()
@app.post("/webhooks/mailgent")
async def webhook(request: Request):
raw = await request.body()
ok = verify_webhook(
raw,
request.headers.get("x-mailgent-signature"),
os.environ["MAILGENT_WEBHOOK_SECRET"],
)
if not ok:
raise HTTPException(400, "invalid signature")
# de-dupe on x-mailgent-idempotency-key, then handle the event.
# Today the only event type is `payment.received`.
Quick start
from mailgent import Mailgent
client = Mailgent(api_key="mgnt-...")
me = client.identity.whoami()
print(me.email)
client.mail.send(
to=["colleague@example.com"],
subject="Hello from my agent",
text="Sent via the Mailgent Python SDK.",
)
Async usage
from mailgent import AsyncMailgent
async with AsyncMailgent(api_key="mgnt-...") as client:
me = await client.identity.whoami()
await client.mail.send(
to=["colleague@example.com"],
subject="Hello",
text="Sent asynchronously.",
)
Authentication
Pass your API key directly, or set the MAILGENT_API_KEY environment variable:
# Explicit
client = Mailgent(api_key="mgnt-...")
# From environment
import os
os.environ["MAILGENT_API_KEY"] = "mgnt-..."
client = Mailgent()
Both Mailgent and AsyncMailgent support context managers for automatic resource cleanup:
with Mailgent() as client:
me = client.identity.whoami()
Usage
Identity
me = client.identity.whoami()
print(me.email, me.display_name)
Vault
The vault is password-manager-style encrypted secret storage (AES-256-GCM at rest). Use client.vault.store() for arbitrary types, or the typed helpers below.
# Simple API key
client.vault.store_api_key("stripe", "sk_live_...")
# OAuth-style client credentials (client id + secret)
client.vault.store_api_key("twitter", {
"clientId": "abc123",
"secret": "def456",
})
# Credit card (encrypted at rest — this is a secret vault, not a payment processor)
client.vault.store_card("personal-visa", {
"cardholder": "Jane Doe",
"number": "4242 4242 4242 4242",
"expMonth": "12",
"expYear": "2029",
"cvc": "123",
"zip": "94103",
}, metadata={"brand": "Visa"})
# Shipping address
client.vault.store_shipping_address("home", {
"name": "Autonomous Agent",
"line1": "1 Demo Way",
"city": "San Francisco",
"state": "CA",
"postcode": "94103",
"country": "US",
})
Supported credential types: LOGIN, API_KEY, OAUTH, TOTP, SSH_KEY, DATABASE, SMTP, AWS, CERTIFICATE, CARD, SHIPPING_ADDRESS, CUSTOM.
Slack
Bridge your agent into a Slack workspace. Connect once via OAuth, then send and read messages (scopes: slack:read / slack:send).
# One-time setup: open the install link in a browser
link = client.slack.connect()
print(link.install_url)
# Check the connection
conn = client.slack.connection()
print(conn.connected, conn.team_name)
# Find a channel and send a message
channels = client.slack.list_channels()["channels"]
ack = client.slack.send_message("#general", "Deploy finished ✅")
# Reply in a thread
client.slack.send_message("#general", "Logs attached.", thread_ts=ack.ts)
# Read messages received by the bot
messages = client.slack.list_messages(channel="#general", limit=20)["messages"]
Social
Post to connected social media accounts (scopes: social:read / social:write). Accounts are connected in the console — there is no connect endpoint.
# See what's connected
accounts = client.social.list_accounts()["accounts"]
# Post everywhere (omit account_ids/platforms to target every account)
post = client.social.create_post("We just shipped v2! 🚀")
# Target specific platforms, attach media, or schedule for later
client.social.create_post(
"Launch day!",
platforms=["twitter", "linkedin"],
media_urls=["https://example.com/banner.png"],
scheduled_at="2026-07-01T09:00:00Z",
)
# Check delivery results
detail = client.social.get_post(post.post_id)
More resources
The SDK also exposes client.mail, client.calendar, client.logs, and client.did. See the full reference at docs.mailgent.dev for request/response shapes, pagination, and end-to-end examples.
Error handling
All API errors raise MailgentApiError with structured fields:
from mailgent import MailgentApiError
try:
client.mail.send(to=["a@b.com"], subject="Hi", text="Hello")
except MailgentApiError as e:
print(e.status) # HTTP status code
print(e.code) # Error code string
print(e.message) # Human-readable message
Types
The SDK returns typed dataclasses, not raw dictionaries. API responses are automatically converted from camelCase to snake_case.
| Type | Description |
|---|---|
IdentityResponse |
Agent identity details |
MessageResponse |
Email message |
ThreadResponse |
Thread summary |
ThreadDetailResponse |
Thread with messages |
CredentialMetadata |
Vault credential metadata |
CredentialWithData |
Credential with decrypted data |
ActivityLog |
Single activity log entry |
LogsStats |
Aggregated log statistics |
TotpResponse |
Generated TOTP code |
DidDocument |
DID document |
SlackConnection |
Slack workspace connection status |
SlackChannel |
Slack channel visible to the bot |
SlackMessage |
Slack message received by the bot |
SocialAccount |
Connected social media account |
CreateSocialPostResponse |
Result of creating a social post |
Note: The
fromfield in message responses is exposed asfrom_addrssincefromis a reserved keyword in Python.
Requirements
- Python 3.9+
httpx(installed automatically)
Links
License
MIT
Release files for mailgent-sdk 0.7.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| mailgent_sdk-0.7.1.tar.gz | 32.9 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| mailgent_sdk-0.7.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 59.5 kB
Release files / mailgent_sdk-0.7.1.tar.gz
| Download URL | mailgent_sdk-0.7.1.tar.gz |
|---|---|
| Size | 32.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5f37badce003c4f37f9302ac98fd30126e77f3a2cef955f3414274f7ca61bdd1
|
|
BLAKE2b-256 checksum How to use checksums |
44ab02598f7bbcff892d48b7f3828ae20eaedf332df4b992fcb0f1ac88552aad
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.5
|
Release files / mailgent_sdk-0.7.1-py3-none-any.whl
| Download URL | mailgent_sdk-0.7.1-py3-none-any.whl |
|---|---|
| Size | 26.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
8cabe57c4a44b9bf21a1ab840121eefdca7c85648e2ae012678c54e67505fca1
|
|
BLAKE2b-256 checksum How to use checksums |
554730132979f2e97db3e595c682dc5d99ff5ce146df026975ff507b8e8c9e59
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.5
|