mxgate for Python
Python client for mxgate: 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
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:
- The
api_keyargument:Mxgate("mxg_..."). - The environment variable
MXGATE_API_KEY. - The field
api_keyin~/.config/mxgate/config.json. ThemxgateCLI writes this file. IfXDG_CONFIG_HOMEis 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.
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.
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.
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
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
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
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
Metadata
Release files for mxgate 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| mxgate-0.3.0.tar.gz | 15.9 kB | Without provenance | Details for mxgate-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| mxgate-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for mxgate-0.3.0-py3-none-any.whl |
Total release size: 34.4 kB
Release files / mxgate-0.3.0.tar.gz
| Download URL | mxgate-0.3.0.tar.gz |
|---|---|
| Size | 15.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
25c1b4aa3fc24a562ab0483a2ef50f6a9936cce4886eb6604ca634238d28753e
|
|
BLAKE2b-256 checksum How to use checksums |
a5fbf2048e5288a70b2a9233a1721e8f4236d5057378e541250449311a98aa17
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.16 {"installer":{"name":"uv","version":"0.12.16","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / mxgate-0.3.0-py3-none-any.whl
| Download URL | mxgate-0.3.0-py3-none-any.whl |
|---|---|
| Size | 18.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4e62bb0f0f15992e6c8811fda24305358e0b14592a494df70352e3cd3d9b0efa
|
|
BLAKE2b-256 checksum How to use checksums |
3871dabb09153a6ef361a725009c094d0b66015b8cc6083ff09a0f4a314b3333
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.16 {"installer":{"name":"uv","version":"0.12.16","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for mxgate 0.3.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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.