Send email with Python
Prerequisites
Before you start, you need:
- A mails.ai API key. A test key (
mk_test_…) runs everything on this page and sends no real email. - Python 3.10 or newer.
Guide
Install
Get the mails.ai Python SDK. It is one package,
mailsai, and it bringshttpxwith it.pip install mailsaiuv add mailsaipoetry add mailsaiSet your API key
Put the key in an environment variable. The SDK reads
MAILS_API_KEYon its own, so the key never appears in your code.export MAILS_API_KEY="mk_test_xxxxxxxx"Send an email
One call sends the message.
fromnames the agent that sends it: an agent with that name is used if it exists, and created if it does not when the key may create agents (themanagescope) and your plan has room for another; withoutmanagethe send answers403 insufficient_scope. Becausefromis a reserved word in Python, the fields go in a dictionary.from mailsai import Client client = Client() # reads MAILS_API_KEY message = { "from": "hello", "to": "reply@test.mails.ai", "subject": "Welcome aboard", "body": "Thanks for signing up. Reply any time.", } sent = client.send(**message) print(sent["id"], sent["status"], sent["from"])reply@test.mails.aiis an address of ours that answers within about a second, so you can test a whole conversation without writing to a real person.sent["from"]is the address the message was sent as. How the test address works.Read the reply
Every email your agent receives becomes an event. A reply to something the agent sent is a
reply.receivedevent, and it carries aninjection_scorefrom 0 to 1.from mailsai import Client client = Client() events = client.list_events( event_type="reply.received", limit=5 ) for event in events["data"]: reply = event["data"] print(reply["from"]["address"], reply["subject"]) print("injection score:", event["injection_score"])
Handle errors
Any answer that is not a success raises MailsError. Its code is the stable thing to branch on, and Errors lists every code.
from mailsai import Client, MailsError
client = Client()
try:
client.send(
to="reply@test.mails.ai",
subject="Hello",
body="A short test.",
)
except MailsError as error:
print(error.status, error.code, error.message)
print("request id:", error.request_id)422 cold_email_prohibited. With a test key the same message succeeds and the answer carries classifier_warning, so you can check a template before going live.Next steps
Was this page helpful?