Official Python SDK for the Mailgent API — identity, mail, vault, calendar, and buyer x402 payments for AI agents
Project description
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="loid-...")
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="loid-...") 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="loid-...")
# From environment
import os
os.environ["MAILGENT_API_KEY"] = "loid-..."
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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mailgent_sdk-0.7.0.tar.gz.
File metadata
- Download URL: mailgent_sdk-0.7.0.tar.gz
- Upload date:
- Size: 32.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
833e0917fa076a694d2b40d434e52cf258d3d43c02cf2191e8a204b736579cb0
|
|
| MD5 |
5f532710188f38184531cb28399ac6ee
|
|
| BLAKE2b-256 |
b23ee44dcf3aaa913d691e8ecce37036544895795f8357a4cb7ac647ecd6d102
|
File details
Details for the file mailgent_sdk-0.7.0-py3-none-any.whl.
File metadata
- Download URL: mailgent_sdk-0.7.0-py3-none-any.whl
- Upload date:
- Size: 26.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4b5af29ef3d295f7cf4c488d90eb9dc52af5b1f02dacaae3cb96fe1b462d4be6
|
|
| MD5 |
d8379dcd2be7d42ff69bdf140177f9d7
|
|
| BLAKE2b-256 |
a8cf91b35d2d9286a3d44d4124f7897de7d80a00b82bb92bdc7ecd3dac973e77
|