Skip to content

mailgent-dev/mailgent-python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mailgent Python SDK

The official Python SDK for the Mailgent API -- identity, mail, vault, calendar, and Mailgent Pay for AI agents.

PyPI version Python 3.9+ License: MIT

Installation

pip install mailgent-sdk

The distribution is mailgent-sdk on PyPI, but the import name is mailgent.

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 from field in message responses is exposed as from_addrs since from is a reserved keyword in Python.

Requirements

  • Python 3.9+
  • httpx (installed automatically)

Links

License

MIT

About

Official Python SDK for Mailgent — identity, mail, vault, calendar, DID + buyer-side x402 payments for AI agents.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages