Skip to main contentSkip to footer
ExamplescriptintermediateRunnablememory-lab

Email Example

Runnable example (intermediate) for script using mem0, python-dotenv.

Key Facts

Level
intermediate
Runtime
Python • Mem0 + Python Dotenv
Pattern
Memory-aware assistance with legible context
Interaction
Live sandbox • Script
Updated
14 March 2026

Navigate this example

High-level flow

How this example moves from input to execution and reviewable output
Email Example -> User request -> System execution -> Reviewable output -> Ensure that background work… -> Align feedback with the…

Start

Email Example

Checkpoint

User request

Outcome

System execution

Why this page exists

This example is shown as both real source code and a product-facing interaction pattern so learners can connect implementation, UX, and doctrine without leaving the library.

Visual flowReal sourceSandbox or walkthroughMCP access
How should this example be used in the platform?

Use the sandbox to understand the experience pattern first, then inspect the source to see how the product boundary, model boundary, and doctrine boundary are actually implemented.

UX pattern: Memory-aware assistance with legible context
Ensure that background work remains perceptible
Align feedback with the user’s level of attention
Establish trust through inspectability
Source references
Library entry
knowledge-mem0-cloud-email-example
Source path
content/example-library/sources/knowledge/mem0/cloud/email_example.py
Libraries
mem0, python-dotenv
Runtime requirements
Local repo environment
Related principles
Ensure that background work remains perceptible, Align feedback with the user’s level of attention, Establish trust through inspectability

email_example.py

python
from mem0 import MemoryClient
from email.parser import Parser
from dotenv import load_dotenv

load_dotenv("../.env")


# Initialize Mem0 client
client = MemoryClient()


class EmailProcessor:
    def __init__(self):
        """Initialize the Email Processor with Mem0 memory client"""
        self.client = client

    def process_email(self, email_content, user_id):
        """
        Process an email and store it in Mem0 memory

        Args:
            email_content (str): Raw email content
            user_id (str): User identifier for memory association
        """
        # Parse email
        parser = Parser()
        email = parser.parsestr(email_content)

        # Extract email details
        sender = email["from"]
        recipient = email["to"]
        subject = email["subject"]
        date = email["date"]
        body = self._get_email_body(email)

        # Create message object for Mem0
        message = {
            "role": "user",
            "content": f"Email from {sender}: {subject}\n\n{body}",
        }

        # Create metadata for better retrieval
        metadata = {
            "email_type": "incoming",
            "sender": sender,
            "recipient": recipient,
            "subject": subject,
            "date": date,
        }

        # Store in Mem0 with appropriate categories
        response = self.client.add(
            messages=[message],
            user_id=user_id,
            metadata=metadata,
            categories=["email", "correspondence"],
            version="v2",
        )

        return response

    def _get_email_body(self, email):
        """Extract the body content from an email"""
        # Simplified extraction - in real-world, handle multipart emails
        if email.is_multipart():
            for part in email.walk():
                if part.get_content_type() == "text/plain":
                    return part.get_payload(decode=True).decode()
        else:
            return email.get_payload(decode=True).decode()

    def search_emails(self, query, user_id):
        """
        Search through stored emails

        Args:
            query (str): Search query
            user_id (str): User identifier
        """
        # Search Mem0 for relevant emails
        results = self.client.search(
            query=query,
            user_id=user_id,
            categories=["email"],
            output_format="v1.1",
            version="v2",
        )

        return results

    def get_email_thread(self, subject, user_id):
        """
        Retrieve all emails in a thread based on subject

        Args:
            subject (str): Email subject to match
            user_id (str): User identifier
        """
        filters = {
            "AND": [
                {"user_id": user_id},
                {"categories": {"contains": "email"}},
                {"metadata": {"subject": {"contains": subject}}},
            ]
        }

        thread = self.client.get_all(
            version="v2", filters=filters, output_format="v1.1"
        )

        return thread


# Initialize the processor
processor = EmailProcessor()

# Example raw email
sample_email = """From: alice@example.com
To: bob@example.com
Subject: Meeting Schedule Update
Date: Mon, 15 Jul 2024 14:22:05 -0700

Hi Bob,

I wanted to update you on the schedule for our upcoming project meeting.
We'll be meeting this Thursday at 2pm instead of Friday.

Could you please prepare your section of the presentation?

Thanks,
Alice
"""

# Process and store the email
user_id = "bob@example.com"
processor.process_email(sample_email, user_id)

# Later, search for emails about meetings
meeting_emails = processor.search_emails("meeting schedule", user_id)
print(f"Found {len(meeting_emails['results'])} relevant emails")
What should the learner inspect in the code?

Look for the exact place where system scope is bounded: schema definitions, prompt framing, runtime configuration, and the call site that turns user intent into a concrete model or workflow action.

Look for output contracts and validation
Look for the exact execution call
Look for what the product could expose to the user
How does the sandbox relate to the source?

The sandbox should make the UX legible: what the user sees, what the system is deciding, and how the result becomes reviewable. The source then shows how that behavior is actually implemented.

Enter a message or load a memory scenario.
Run the context recall step.
Inspect both the recalled memory and the personalized reply.
SandboxMemory-aware assistance with legible context
Memory lab

This experience makes it clear what the system remembers, what it retrieves, and how that context changes the reply.

UX explanation

Memory examples are only trustworthy when the user can understand which information was recalled and why it changes the response.

AI design explanation

Memory is not just persistence. It is a product choice about what to store, what to recall, and how to make the effect of context inspectable.

Interaction walkthrough

  1. 1Enter a message or load a memory scenario.
  2. 2Run the context recall step.
  3. 3Inspect both the recalled memory and the personalized reply.

Message

Recalled memoryNew memory

Recalled context

The recalled context appears here.

Memory to store

The suggested memory write appears here.

Visible reply

The personalized reply appears here.

Used in courses and paths

This example currently stands on its own in the library, but it still connects to the principle system and the broader example family.

Related principles

Runtime architecture

Use this example in your agents

This example is also available through the blueprint’s agent-ready layer. Use the For agents page for the public MCP, deterministic exports, and Claude/Cursor setup.

Define triggers, context, and boundaries before increasing autonomy
Make control, observability, and recovery explicit in the runtime
Choose the right operational patterns before delegating to workflows