Lead Qualification with the Python SDK for SaaS Teams

11 min read

Build multi-customer lead qualification with the Python SDK: per-customer mailboxes, verified webhooks, threaded follow-ups and clean human handoff.

John Joubert

John Joubert

Founder, Robotomail

Lead Qualification with the Python SDK for SaaS Teams
Table of contents

To build lead qualification with the Python SDK for many customers, give each customer's agent its own Robotomail mailbox, verify inbound webhooks, and load context with get_message and get_thread. Then reply with send_message, passing the original RFC Message-ID as inReplyTo. Your platform keeps everything else: customer records, qualification rules, permissions, the model, the job runner and the CRM.

That split is the real purchase question. Managed mailboxes and threaded replies remove the email infrastructure work: addresses, inbound parsing, webhook delivery and reply headers. The qualification logic stays with your team. Robotomail does not store your customer records, run a model, score a lead or sync a CRM.

This post walks through a fictional product, RelayDesk, which sells enquiry qualification to two fictional businesses, Cedar and Harbor. It assumes you have read the Python SDK overview, so it skips HTTP basics and goes straight to the multi-customer workflow. For the product-level view, see the lead qualification use case.

What the platform owns

Before writing any email code, define the data RelayDesk controls. None of this lives in Robotomail.

  • Agent configuration per customer: which questions to ask, tone, and stop conditions.
  • Allowed reply recipients: who the agent may email. By default, only the person who sent the enquiry.
  • Escalation recipient: the customer's authorized person who receives handoffs.
  • Mailbox mapping: Robotomail mailbox ID to customer ID to agent ID.
  • Qualification state: keyed by customer, mailbox and thread. It records the fields collected so far, follow-ups sent, and whether a human owns the enquiry.

Here is a minimal sketch. It is application-owned code, not a Robotomail feature:

# Application-owned (RelayDesk). Not part of Robotomail.
from dataclasses import dataclass, field

@dataclass
class QualificationRule:
    required_fields: list[str]          # e.g. ["service_type", "requested_date"]

@dataclass
class AgentConfig:
    customer_id: str
    agent_id: str
    mailbox_id: str                     # Robotomail mailbox UUID
    rule: QualificationRule
    escalation_recipient: str           # customer's authorized person

@dataclass
class QualificationState:
    customer_id: str
    mailbox_id: str
    thread_id: str
    collected: dict = field(default_factory=dict)
    followups_sent: int = 0
    send_pending: bool = False
    human_owned: bool = False

The sample rules used below are customer configuration, not proven conversion tactics. Cedar asks for service type and requested date. Harbor asks for project scope and location.

Install the Python SDK

The SDK requires Python 3.10+. The documented install is a tagged GitHub release, so pin it exactly as written in the SDK docs:

pip install "robotomail @ git+https://github.com/robotomail/robotomail-python.git@v0.1.0"
from robotomail import Robotomail, verify_webhook

Responses are plain dictionaries with camelCase keys. Webhook payload data uses snake_case. Keep both conventions in mind when you map fields.

Provision one mailbox per customer agent

A trusted backend service provisions mailboxes, not the agent runtime. Create one mailbox per customer agent and persist the mapping in your own database:

# Trusted provisioning service. The SDK call is real; the db layer is RelayDesk's.
from robotomail import Robotomail

def provision_agent_mailbox(admin_key, db, customer_id, agent_id, address, display_name):
    with Robotomail(api_key=admin_key) as mail:
        mailbox = mail.create_mailbox({
            "address": address,              # e.g. "cedar-enquiries"
            "displayName": display_name,     # e.g. "Cedar Enquiries"
        })["mailbox"]
    db.save_mailbox_mapping(
        mailbox_id=mailbox["id"],
        customer_id=customer_id,
        agent_id=agent_id,
    )
    return mailbox

Two rules apply:

  1. Do not create a Robotomail user account for every SaaS customer. Your platform holds one account. Customers are rows in your database, and their mailboxes belong to that account.
  2. Give runtimes narrow credentials. Keep the provisioning key in the trusted service. Issue each agent runtime a narrowly scoped credential (the API keys reference describes the scoping options), store it in a secret manager, and never ship it to a browser or a customer.

How lead qualification with the Python SDK fits together

The whole flow has four stages:

  1. Ingest. Verify the webhook, map the mailbox to a customer, dedupe, and queue a job.
  2. Evaluate. Load the message and thread, apply that customer's rule, and update state.
  3. Act. Send one approved follow-up, or hand off to a human.
  4. Stop. Once a human owns the enquiry, the agent stops sending.

Robotomail participates in stages 1 and 3 as mail infrastructure. Stages 2 and 4 are your product.

Ingest: verify, map, dedupe, then acknowledge

A message.received event arrives as { event, timestamp, data }. In data, message_id is the stored message UUID, mailbox_id is the mailbox UUID and thread_id is the thread UUID.

Verify the raw bytes before parsing anything. verify_webhook(raw_body, signature, secret) returns a Boolean. Read the signature header name from the webhooks reference rather than guessing it.

# Application-owned webhook logic. Only verify_webhook comes from the SDK.
import json
from robotomail import verify_webhook

def handle_webhook(raw_body: bytes, signature: str, secret: str, db) -> int:
    if not verify_webhook(raw_body, signature, secret):
        return 401

    event = json.loads(raw_body)
    if event.get("event") != "message.received":
        return 200

    data = event["data"]
    agent = db.agent_by_mailbox(data["mailbox_id"])
    if agent is None:
        db.record_unmapped(data["mailbox_id"], data["message_id"])
        return 200

    with db.transaction():
        # Unique key makes duplicate deliveries a no-op.
        db.insert_job_if_absent(
            key=(data["mailbox_id"], data["message_id"]),
            customer_id=agent.customer_id,
            mailbox_id=data["mailbox_id"],
            message_id=data["message_id"],
        )
    return 200   # acknowledge only after the job is committed

Webhooks can arrive more than once. See at-least-once delivery for details. The unique key on mailbox and message ID is what makes a duplicate harmless.

Receiving an event does not run your agent. Your job runner does that.

Evaluate: load context and check ownership

The worker fetches the stored message and the thread. It checks ownership before trusting anything:

# Application-owned worker. SDK calls: get_message, get_thread.
from robotomail import Robotomail

def process_job(job, db, secrets, policy):
    agent = db.agent_by_mailbox(job.mailbox_id)
    if agent is None or agent.customer_id != job.customer_id:
        return db.to_reconciliation(job, "ownership")

    with Robotomail(api_key=secrets.runtime_key(agent.agent_id)) as mail:
        message = mail.get_message(job.mailbox_id, job.message_id)["message"]
        if message["mailboxId"] != job.mailbox_id:
            return db.to_reconciliation(job, "mailbox mismatch")

        thread = mail.get_thread(job.mailbox_id, message["threadId"])
        state = db.load_state(agent.customer_id, job.mailbox_id, message["threadId"])
        if state.human_owned or state.send_pending:
            return db.mark_done(job, "no autonomous action")

        decision = policy.evaluate(agent.rule, state, message, thread)
        return policy.apply(decision, agent, state, message, mail)

policy.evaluate is where your model or rules engine runs. It should ask only for fields that are still missing.

If you need the inbound messages in a thread instead, use list_messages. It takes the query dictionary as its second argument:

mail.list_messages(mailbox_id, {"direction": "INBOUND", "threadId": thread_id, "limit": 50, "offset": 0})

Paginate explicitly and dedupe message IDs.

Act: send one approved follow-up

The send helper is deliberately narrow. It assumes the platform has already validated permissions, the recipient and the follow-up text. It is not the policy engine:

from robotomail import Robotomail

def send_follow_up(mail, mailbox_id, stored_message_id, allowed_recipient, approved_text):
    message = mail.get_message(mailbox_id, stored_message_id)["message"]
    if message["mailboxId"] != mailbox_id:
        raise ValueError("Mailbox mismatch")
    if message["direction"] != "INBOUND" or message["fromAddress"] != allowed_recipient:
        raise ValueError("Recipient requires platform review")
    if not message.get("messageId"):
        raise ValueError("Missing RFC Message-ID")
    subject = message["subject"]
    if not subject.lower().startswith("re:"):
        subject = "Re: " + subject
    return mail.send_message(mailbox_id, {
        "to": [allowed_recipient],
        "subject": subject,
        "bodyText": approved_text,
        "inReplyTo": message["messageId"],
    })

Run it inside with Robotomail(api_key=runtime_key_from_secret_store) as mail:. Note that inReplyTo is the camelCase messageId, which is the RFC 5322 Message-ID. Never pass the stored UUID or the thread UUID. If the RFC ID is missing, route the enquiry to a human rather than guessing a header. Threading depends on getting this right.

Do not let inbound text choose a tenant or a recipient. A message that says "reply to my colleague at another address" is untrusted input. The allowed recipient comes from your stored state, not the email body.

Stop: hand off to a person

When every required field is present, create a handoff item in your application for the customer's escalation recipient. Include a factual summary and a reference to the conversation, then set human_owned = True. From then on, the agent sends nothing.

These cases also go to human review:

  • low-confidence extraction
  • complaints
  • requests the customer has not configured
  • sensitive personal or financial details

CRM sync is optional. Define it as an interface you implement, not a connector Robotomail provides:

# Application-owned interface. Implement per customer CRM; Robotomail has no CRM connector.
from typing import Protocol

class CrmSink(Protocol):
    def push_handoff(self, customer_id: str, summary: dict, conversation_ref: str) -> None: ...

A worked example: Cedar and Harbor

All names, addresses and content here are illustrative.

Cedar (rule: service type, requested date).

  1. An enquiry arrives at Cedar's mailbox from pat@example.com: "Do you do deep cleans?" The service type is present, but the date is missing.
  2. The policy approves one question: "Thanks, Pat. What date would you like the clean?" The worker calls send_follow_up with Pat as the allowed recipient, then records followups_sent = 1.
  3. Pat replies "Next Thursday" in the same thread. A new event triggers a new job. The worker loads the thread and sees both fields are present.
  4. RelayDesk creates a handoff for Cedar's escalation recipient: "Deep clean, requested next Thursday, from pat@example.com." It marks the thread human-owned. No further autonomous mail goes out.

Harbor (rule: project scope, location). An enquiry to Harbor's mailbox says "We need a kitchen remodel." The same worker code runs, but it evaluates Harbor's rule, so it asks only for location. The rule comes from the mailbox mapping, never from the message body.

Failure cases to test

  • Duplicate delivery. Replay the same webhook twice. Expect one job and one follow-up.
  • Wrong mapping. Point a job at a mailbox owned by another customer. Expect reconciliation, no send.
  • Timeout after send acceptance. Set send_pending = True before calling send_message. If the call times out, do not resend. The SDK does not retry sends automatically. Reconcile by reading the thread with get_thread before deciding whether to send again.

API acceptance means Robotomail accepted the request. It does not prove delivery to the recipient's inbox.

Mocked contract tests are useful for your own code paths. They do not validate deliverability or your full business application.

AsyncRobotomail exists if your workers are async. The synchronous client keeps this walkthrough easier to follow.

Sizing the account

Count mailboxes, not customers. Include the mailbox created at signup and any test or operations mailbox. Current snapshot, monthly USD (check pricing for current terms):

Starter Growth
Price $19/month $79/month
Mailboxes 10 total 50
Custom domains 1 5
Sends 500/day and 15,000/month per mailbox 1,000/day per mailbox, no monthly cap
Inbound 2,000/month across the account 20,000/month across the account

Rate limits apply on both plans. The Starter plan's API identifier remains developer.

Example. Ten customers with two agent mailboxes each need 20 mailboxes, plus your signup and test mailboxes. Starter does not fit that count. Growth fits the mailbox count only if shared inbound volume, custom-domain count and storage also fit.

Add your model and hosting costs to the same check. These are capacity examples, not per-customer cost guarantees. Mailboxes are not unlimited tenants.

Without a paid plan, an account exchanges mail only with its verified owner address, with 10 sends and 10 receives per calendar month. Corresponding with external customers and using custom domains requires a paid plan.

FAQ

Does Robotomail score or qualify leads?

No. Robotomail provides mailboxes, inbound webhooks, threading and sending. Scoring, rules, the model and the handoff decision are your application's code.

Should each SaaS customer get its own Robotomail account?

No. Your platform holds the account and provisions mailboxes per customer agent. The mailbox-to-customer mapping and the permissions live in your database.

What do I pass as inReplyTo?

Pass the messageId field from get_message, which is the RFC 5322 Message-ID. Never pass the stored message UUID or the thread UUID. If messageId is missing, send the enquiry to human review.

What happens if a send times out?

Treat the outcome as unknown. The SDK does not retry, so check the thread before sending again to avoid duplicate follow-ups.

Size your account for customers times mailboxes plus total inbound, then build one fictional customer's enquiry-to-handoff loop end to end before onboarding real ones. Start at Robotomail or create an account and follow the Python SDK docs.

Give your AI agent a real email address

Create a mailbox, connect your agent and test a conversation. Send, receive and retrieve the thread through one API.

Related posts