Skip to main content

Send email with Python

Install mailsai, set MAILS_API_KEY, send one message, and read the reply your agent gets back.
Use this pre-built prompt to get started faster.
Open in Cursor

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

  1. Install

    Get the mails.ai Python SDK. It is one package, mailsai, and it brings httpx with it.

    pip install mailsai
  2. Set your API key

    Put the key in an environment variable. The SDK reads MAILS_API_KEY on its own, so the key never appears in your code.

    export MAILS_API_KEY="mk_test_xxxxxxxx"
  3. Send an email

    One call sends the message. from names 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 (the manage scope) and your plan has room for another; without manage the send answers 403 insufficient_scope. Because from is a reserved word in Python, the fields go in a dictionary.

    send.py
    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.ai is 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.

  4. Read the reply

    Every email your agent receives becomes an event. A reply to something the agent sent is a reply.received event, and it carries an injection_score from 0 to 1.

    replies.py
    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.

errors.py
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)
mails.ai sends transactional email: messages a person’s own action or account calls for. Cold outreach is refused with 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?