Metadata-Version: 2.5
Name: mxgate
Version: 0.3.0
Summary: Python client for mxgate: email forwarding and send-as for a domain you own.
Project-URL: Homepage, https://mxgate.io
Project-URL: Documentation, https://mxgate.io/docs/sdks
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agent,api-client,dkim,dns,email,email-forwarding,mx,send-as,smtp,webhook
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# mxgate for Python

Python client for [mxgate](https://mxgate.io): email forwarding and send-as for a domain you own.

mxgate receives mail for your domain and forwards it to mailboxes that you confirm. It also sends mail as addresses at your domain. This package calls the HTTP API at `https://api.mxgate.io`.

Python 3.9 or newer, no dependencies.

## Install

```
pip install mxgate
```

## Quick start

```python
from mxgate import Mxgate

mx = Mxgate()  # the key comes from MXGATE_API_KEY
added = mx.add_domain("example.com")
for record in added["domain"]["records"]:
    print(record["type"], record["name"], record["value"])
# Publish the records at your DNS host. Then:
if mx.verify_domain("example.com")["verified"]:
    mx.set_alias("*@example.com", "you@gmail.com")
    mx.send("Ann <hello@example.com>", "client@example.org", "Hello", "Sent with mxgate.")
for entry in mx.logs(domain="example.com", limit=10)["entries"]:
    print(entry["received_at"], entry["status"], entry["recipient"])
```

DNS changes can take some minutes. Call `verify_domain` again until `verified` is true.

`send` needs the DKIM record of the domain. `mx.send_as("example.com")["send_as"]["ready"]` is true when the domain can send.

No account yet? `Mxgate().signup("you@gmail.com")` returns the key in `api_key`. The key is shown one time. Store it.

Each method returns the JSON answer of the API as a `dict`. The types in `mxgate.types` are `TypedDict` definitions, so an editor shows the fields.

## Where the key is read from

The client uses the first key that it finds:

1. The `api_key` argument: `Mxgate("mxg_...")`.
2. The environment variable `MXGATE_API_KEY`.
3. The field `api_key` in `~/.config/mxgate/config.json`. The `mxgate` CLI writes this file. If `XDG_CONFIG_HOME` is set, the file is `$XDG_CONFIG_HOME/mxgate/config.json`.

The base URL is `https://api.mxgate.io`. To change it, give `api_url` to `Mxgate()`, set `MXGATE_API_URL`, or set `api_url` in the config file.

`Mxgate(timeout=10)` sets the time limit of one call in seconds. The default is 30.

## Errors

An error answer of the API raises `MxgateError`. A method never returns an error body.

```python
import time
from mxgate import Mxgate, MxgateError

mx = Mxgate()
try:
    mx.add_domain("example.com")
except MxgateError as err:
    if err.code == "rate_limited":
        time.sleep(err.retry_after_seconds or 60)
    elif err.code == "plan_limit":
        print(err.message, err.upgrade_url)
    else:
        print(err.status, err.code, err.message)
        print("Next step:", err.fix)
```

| Attribute | Meaning |
| --- | --- |
| `status` | The HTTP status. 0 when no answer came. |
| `code` | The `error` field. Let your program switch on it. |
| `message` | One sentence for a person. Do not parse it. |
| `fix` | The next step, or `None`. Most errors have it. |
| `retry_after_seconds` | Only with `rate_limited`: how long to wait. |
| `upgrade_url` | Only with `plan_limit`: the page with the plans. |
| `body` | The full error body as a `dict`. |

`str(err)` is `"<code>: <message>"`, then `Fix: <fix>` when there is a fix.

The client adds three codes of its own:

- `network` (status 0): no answer came. The host is wrong, the network is down, or the time limit ended.
- `no_api_key` (status 401): the client found no key. It made no call.
- `bad_response`: the answer was not a JSON object, or the API URL redirects.

An address for `set_alias` or `remove_alias` that is not an alias address raises `ValueError`. The client makes no call.

The full list of codes is at https://mxgate.io/docs/errors.

## Check a webhook call

mxgate signs each webhook call. The header `mxgate-signature` is `t=<unix seconds>,v1=<hex>`. `v1` is the HMAC-SHA256 of `"<t>.<raw body>"` with your `webhook_secret`.

```python
import json
from mxgate import verify_webhook

def handle(headers, raw_body: bytes) -> int:
    if not verify_webhook(WEBHOOK_SECRET, headers.get("mxgate-signature", ""), raw_body):
        return 400
    event = json.loads(raw_body)
    print(event["type"], event["data"])
    return 200
```

Give the body as the bytes that came, before a JSON parser changes them. The function returns `False` when the signature is wrong or when `t` is more than 300 seconds old. `tolerance_seconds` changes this limit.

To get a secret, set a webhook: `mx.set_notifications(webhook_url="https://example.com/hook")`. That answer shows `webhook_secret` in full. Later answers show only its first characters.

## Methods

| Method | API call | What it does |
| --- | --- | --- |
| `signup(email)` | `POST /v1/signup` | Creates an account. Returns the key one time. No key necessary. |
| `account()` | `GET /v1/account` | The plan, the limits, the usage and the subscription. |
| `keys()` | `GET /v1/keys` | The keys that work now. Only the first 12 characters of each. |
| `recover_key(email)` | `POST /v1/keys/recover` | Mails a recovery token for a lost key. No key necessary. |
| `confirm_recovery(token)` | `POST /v1/keys/recover/confirm` | Gives a new key for the token. Older keys stop. No key necessary. |
| `rotate_key()` | `POST /v1/keys/rotate` | Gives a new key. The key of the client and older keys stop. |
| `apps()` | `GET /v1/oauth/apps` | The apps that are connected to the account through OAuth. |
| `remove_app(app_id)` | `DELETE /v1/oauth/apps/{id}` | Disconnects an app. Its token stops working. |
| `checkout(interval="month")` | `POST /v1/billing/checkout` | A payment link for the paid plan. A person opens it. |
| `billing_portal()` | `POST /v1/billing/portal` | A link for a person: card, invoices, cancel. |
| `domains()` | `GET /v1/domains` | The domains of the account. |
| `add_domain(name)` | `POST /v1/domains` | Adds a domain. Returns the DNS records to publish. |
| `domain(name)` | `GET /v1/domains/{domain}` | One domain with its records and its last check. |
| `verify_domain(name)` | `POST /v1/domains/{domain}/verify` | Checks the DNS records now. |
| `remove_domain(name)` | `DELETE /v1/domains/{domain}` | Removes the domain, its aliases and its SMTP logins. |
| `aliases(domain)` | `GET /v1/domains/{domain}/aliases` | The aliases of the domain. |
| `set_alias(address, to)` | `PUT /v1/domains/{domain}/aliases/{alias}` | Creates or replaces an alias. `to` is one mailbox or a list. |
| `remove_alias(address)` | `DELETE /v1/domains/{domain}/aliases/{alias}` | Removes an alias. |
| `destinations()` | `GET /v1/destinations` | The mailboxes that the account can forward to. |
| `add_destination(email)` | `POST /v1/destinations` | Adds a mailbox. A confirmation link is mailed to it. |
| `send_as(domain)` | `GET /v1/domains/{domain}/smtp` | The send-as state, the SMTP host, the ports and the logins. |
| `create_smtp_credential(domain)` | `POST /v1/domains/{domain}/smtp` | Makes an SMTP login. The password is shown one time. |
| `remove_smtp_credential(domain, username)` | `DELETE /v1/domains/{domain}/smtp/{username}` | Removes an SMTP login. |
| `send(from_, to, subject, text, ...)` | `POST /v1/send` | Sends one plain-text message. |
| `logs(...)` | `GET /v1/logs` | One page of the message log, newest first. |
| `iter_logs(...)` | `GET /v1/logs` | Each row of the log. It gets the next pages for you. |
| `notifications()` | `GET /v1/notifications` | The notification settings and the 20 newest notifications. |
| `set_notifications(...)` | `PUT /v1/notifications` | Changes the email digest, the events and the webhook. |
| `test_webhook()` | `POST /v1/notifications/test` | Sends a signed test call to the webhook. |
| `status()` | `GET /status` | The health of the service for 30 days. No key necessary. |
| `index()` | `GET /` | The version and one line for each endpoint. No key necessary. |
| `login(email)` | `POST /v1/login` | Mails a sign-in code. For the website. No key necessary. |
| `confirm_login(email, code)` | `POST /v1/login/confirm` | Gives a session token for the code. No key necessary. |
| `logout()` | `POST /v1/logout` | Ends the session of the token that the client uses. |
| `google_login_url(state)` | `GET /v1/login/google` | Returns the URL of the sign-in with Google, for a browser. It makes no call. |
| `confirm_login_grant(grant)` | `POST /v1/login/grant` | Gives a session token for the grant of the sign-in with Google. No key necessary. |

### Alias addresses

`set_alias` and `remove_alias` take a full address. `hello@example.com` is the alias `hello` of `example.com`. `*@example.com` is the catch-all: it gets mail for each address of the domain that has no alias.

```python
mx.set_alias("hello@example.com", ["you@gmail.com", "client@example.org"])
mx.remove_alias("hello@example.com")
```

A destination that is new to the account gets a confirmation mail. mxgate forwards no mail to it before its owner confirms.

### Send a message

```python
mx.send(
    "Ann <hello@example.com>",
    ["client@example.org"],
    "Re: Offer",
    "Thank you for the offer.",
    cc="you@gmail.com",
    in_reply_to="4f2a9c1e@example.org",
    idempotency_key="offer-reply-1",
)
```

The optional fields are `cc`, `bcc`, `reply_to`, `in_reply_to`, `references`, `copy_to_owner` and `idempotency_key`. Give an `idempotency_key`: a second call with the same key sends nothing and returns the first answer. Then a retry after an error cannot send a second copy.

### Read the log

```python
for entry in mx.iter_logs(domain="example.com", status="bounced"):
    print(entry["recipient"], entry["explanation"])
```

The filters of `logs` and `iter_logs` are `domain`, `direction` (`in` or `out`), `status`, `address`, `before` and `limit`. `logs` returns one page; `next_before` of the page is `before` of the next page. `iter_logs` reads all pages.

### Notifications

```python
mx.set_notifications(email=True, events=["bounced", "expired"])
mx.set_notifications(webhook_url="https://example.com/hook")
mx.set_notifications(webhook_url=None)  # removes the webhook
```

A setting that you do not give stays as it is.

## Tests

```
cd sdk/python
python3 -m unittest discover -s tests -v
```

The tests use a local HTTP server. They make no call to mxgate.

## License

MIT
