Email from Modal Serverless Agent Functions

Send, read, and manage email from Modal's serverless containers — with MultiMail's API-level oversight ensuring every email is properly gated.


Modal is a serverless platform for running Python code in the cloud with instant container spin-up, GPU support, and scheduled functions. When your Modal functions run agent workloads that need email capabilities, MultiMail provides the email infrastructure with oversight that works at the API level — critical for serverless environments where process-level controls don't apply.

The serverless model means your code runs in ephemeral containers that spin up and down dynamically. MultiMail's stateless REST API is ideal for this pattern: each container makes authenticated API calls without needing persistent connections or local state for email management.

Integration is clean: add MultiMail API calls to your Modal functions. Whether it's a scheduled batch job, a webhook handler, or a GPU-powered ML pipeline that generates email reports, MultiMail handles delivery with oversight.

Built for Modal developers

API-Level Oversight for Serverless

In serverless environments, you can't rely on process-level controls. MultiMail's oversight is enforced at the API layer, so every email from every container instance is properly gated regardless of where or how the function runs.

Stateless API for Ephemeral Containers

Modal containers are ephemeral. MultiMail's REST API requires no persistent connections or local state — each API call is self-contained with Bearer token auth, perfect for serverless execution.

Scheduled Email Jobs

Modal's scheduled functions let you run recurring email tasks. MultiMail's oversight ensures scheduled jobs don't send emails unattended — each run's emails are queued for review.

Scale Without Email Safety Concerns

Modal scales containers automatically. Without oversight, a scaling event could multiply email sends. MultiMail's gated_send mode ensures every email from every container instance needs approval.


Get started in minutes

Modal Function with Email Sending
python
import modal
import requests

app = modal.App("email-agent")
image = modal.Image.debian_slim().pip_install("requests")

@app.function(image=image, secrets=[modal.Secret.from_name("multimail")])
def send_report(recipient: str, report_data: dict):
    """Send an email report via MultiMail from a Modal function."""
    import os
    api_key = os.environ["MULTIMAIL_API_KEY"]
    mailbox_id = os.environ["MULTIMAIL_MAILBOX_ID"]

    resp = requests.post(
        "https://api.multimail.dev/v1/send",
        headers={"Authorization": f"Bearer {api_key}"},
        json={
            "mailbox_id": mailbox_id,
            "to": recipient,
            "subject": f"Report: {report_data[&"cm">#039;title']}",
            "body": f"Here is your report:\n\n{report_data[&"cm">#039;summary']}"
        }
    )

    result = resp.json()
    print(f"Email queued for approval: {result.get(&"cm">#039;id')}")
    return result

Create a Modal function that sends email through MultiMail with oversight.

Scheduled Inbox Processing
python
import modal
import requests

app = modal.App("inbox-processor")
image = modal.Image.debian_slim().pip_install("requests")

@app.function(
    image=image,
    secrets=[modal.Secret.from_name("multimail")],
    schedule=modal.Period(minutes=15)
)
def process_inbox():
    """Check inbox every 15 minutes and process new messages."""
    import os
    api_key = os.environ["MULTIMAIL_API_KEY"]
    mailbox_id = os.environ["MULTIMAIL_MAILBOX_ID"]
    headers = {"Authorization": f"Bearer {api_key}"}

    "cm"># Check inbox
    resp = requests.get(
        f"https://api.multimail.dev/v1/mailboxes/{mailbox_id}/inbox",
        headers=headers,
        params={"limit": 20}
    )
    inbox = resp.json()

    for msg in inbox.get("messages", []):
        print(f"Processing: {msg[&"cm">#039;subject']} from {msg['from']}")

        # Draft a reply (queued for approval in gated_send mode)
        requests.post(
            "https://api.multimail.dev/v1/reply",
            headers=headers,
            json={
                "message_id": msg["id"],
                "body": "Thank you for your message. "
                        "We will review and respond shortly."
            }
        )

    print(f"Processed {len(inbox.get(&"cm">#039;messages', []))} messages")

Set up a Modal scheduled function that checks the inbox and processes new messages periodically.

GPU-Powered Email Analysis Pipeline
python
import modal
import requests

app = modal.App("email-analyzer")
gpu_image = modal.Image.debian_slim().pip_install(
    "requests", "transformers", "torch"
)

@app.function(image=gpu_image, gpu="T4",
              secrets=[modal.Secret.from_name("multimail")])
def analyze_and_report(mailbox_id: str, recipient: str):
    """Analyze inbox emails with ML and send a summary report."""
    import os
    api_key = os.environ["MULTIMAIL_API_KEY"]
    headers = {"Authorization": f"Bearer {api_key}"}

    "cm"># Fetch recent emails
    inbox = requests.get(
        f"https://api.multimail.dev/v1/mailboxes/{mailbox_id}/inbox",
        headers=headers, params={"limit": 50}
    ).json()

    "cm"># Analyze with ML model (runs on GPU)
    summaries = []
    for msg in inbox.get("messages", []):
        email = requests.get(
            f"https://api.multimail.dev/v1/emails/{msg[&"cm">#039;id']}",
            headers=headers
        ).json()
        summaries.append(f"- {msg[&"cm">#039;subject']}: {email.get('preview', '')}")

    report = "\n".join(summaries)

    # Send summary report (queued for approval)
    result = requests.post(
        "https://api.multimail.dev/v1/send",
        headers=headers,
        json={
            "mailbox_id": mailbox_id,
            "to": recipient,
            "subject": "Inbox Analysis Report",
            "body": f"Inbox Summary:\n\n{report}"
        }
    ).json()

    return result

Use Modal's GPU support to run ML-powered email analysis with results sent via MultiMail.


Step by step

1

Create a MultiMail Account and API Key

Sign up at multimail.dev, create a mailbox, and generate an API key from your dashboard. Your key will start with mm_live_.

2

Install Modal

Install the Modal client and authenticate.

bash
pip install modal && modal token new
3

Store API Key as Modal Secret

Create a Modal secret named 'multimail' with your API key and mailbox ID.

bash
modal secret create multimail MULTIMAIL_API_KEY=mm_live_your_key MULTIMAIL_MAILBOX_ID=your_id
4

Deploy Your Email Function

Create a Modal function that calls the MultiMail API and deploy it.

bash
modal deploy email_agent.py
5

Approve Pending Emails

Review emails queued by your Modal functions in the MultiMail dashboard. Approve or reject before delivery.


Common questions

How do I store the MultiMail API key in Modal?
Use Modal's secrets management. Create a secret with 'modal secret create multimail MULTIMAIL_API_KEY=mm_live_your_key' and reference it in your function decorator with secrets=[modal.Secret.from_name('multimail')]. The key is available as an environment variable inside the container.
Can Modal's auto-scaling cause duplicate emails?
Modal can run multiple container instances in parallel. If your function logic isn't idempotent, this could cause duplicate email sends. Use MultiMail's gated_send mode as a safety net — duplicates will appear in the approval queue where a human can catch them. Also design your functions to be idempotent.
Does MultiMail work with Modal's scheduled functions?
Yes. Modal's schedule parameter (Period or Cron) triggers function runs on a schedule. Each run makes fresh API calls to MultiMail. In gated_send mode, scheduled runs queue emails for review rather than sending automatically, preventing unattended email delivery.
Can I use MultiMail from Modal GPU functions?
Yes. MultiMail's REST API is a standard HTTPS call that works from any Modal function, including GPU-equipped containers. Use GPU functions for ML-powered email analysis or generation, then send results through MultiMail with full oversight.

Explore more

The only agent email with a verifiable sender

Email infrastructure built for AI agents. Verifiable identity, graduated oversight, and a 38-tool MCP server. Formally verified in Lean 4.