Skip to main content

Overview

The Email extension enables agents to send, receive, and process emails, allowing for automated communication, notifications, and email-based workflows. Agents can compose personalized emails, monitor inboxes, and respond intelligently to incoming messages.

Send Emails

Compose and send personalized emails programmatically

Email Processing

Parse and analyze incoming emails

Smart Responses

Generate contextual email responses

Automation

Create email-based workflows and notifications

How It Works

Email functionality integrates with your existing email infrastructure through APIs or SMTP/IMAP protocols. Agents can:
  1. Compose emails based on natural language instructions
  2. Send emails through configured email services
  3. Monitor inboxes for incoming messages
  4. Parse email content to extract information
  5. Generate responses based on email context

Setup

Configure email integration with your email service provider:
// Configure email tool via MCP
const agentbase = new Agentbase({
  apiKey: process.env.AGENTBASE_API_KEY,
  mcpServers: [{
    name: "email-server",
    transport: "http",
    url: "http://localhost:3000",
    authentication: {
      type: "bearer",
      token: process.env.EMAIL_MCP_TOKEN
    }
  }]
});

Sending Emails

Basic Email Sending

// Send a simple email
const result = await agentbase.runAgent({
  message: `Send an email to [email protected] with:
    Subject: "Project Update"
    Body: "The project is on track and will be completed by Friday."`,
  mode: "base"
});

Personalized Emails

// Send personalized email with data
const customer = {
  name: "Jane Smith",
  email: "[email protected]",
  orderNumber: "12345",
  deliveryDate: "2025-01-15"
};

const result = await agentbase.runAgent({
  message: `Send a personalized order confirmation email to ${customer.email}:

    Hi ${customer.name},

    Your order #${customer.orderNumber} has been confirmed and will be delivered by ${customer.deliveryDate}.

    Thank you for your purchase!`,
  mode: "base"
});

HTML Emails

// Send HTML formatted email
const result = await agentbase.runAgent({
  message: `Send an HTML email to [email protected] with:
    Subject: "Weekly Report"

    Create an HTML email with:
    - A header with our logo
    - A summary of this week's metrics
    - A table showing top performers
    - A footer with unsubscribe link

    Use professional styling with our brand colors.`,
  mode: "base"
});

Email with Attachments

// Send email with attachments
const result = await agentbase.runAgent({
  message: `Send an email to [email protected] with:
    Subject: "Monthly Report"
    Body: "Please find attached the monthly report."
    Attachments: report.pdf, data.xlsx

    The files are in the current directory.`,
  mode: "base"
});

Email Processing

Parse Incoming Emails

// Process received emails
const result = await agentbase.runAgent({
  message: `Check my inbox for unread emails and:
    1. Extract sender, subject, and content
    2. Categorize by type (support, sales, general)
    3. Extract action items
    4. Summarize each email

    Return as JSON.`,
  mode: "base"
});

const emails = JSON.parse(result.content);

Extract Information

// Extract structured data from emails
const result = await agentbase.runAgent({
  message: `Read the email from [email protected] and extract:
    - Order number
    - Items ordered
    - Total amount
    - Expected delivery date

    Return as JSON.`,
  mode: "base"
});

const orderData = JSON.parse(result.content);

Use Cases

1. Automated Customer Support

Respond to customer inquiries automatically:
async function processCustomerEmails() {
  // Get unread support emails
  const result = await agentbase.runAgent({
    message: `Check [email protected] inbox for unread emails and:
      1. Read each email
      2. Categorize the issue type
      3. Generate an appropriate response
      4. Send the response
      5. Mark as read

      For complex issues, mark for manual review.`,
    mode: "base"
  });

  return result.content;
}

// Run periodically
setInterval(processCustomerEmails, 5 * 60 * 1000); // Every 5 minutes

2. Lead Nurturing

Send personalized follow-up emails:
interface Lead {
  email: string;
  name: string;
  company: string;
  interests: string[];
  stage: string;
}

async function nurtureLead(lead: Lead) {
  const result = await agentbase.runAgent({
    message: `Compose a personalized follow-up email for ${lead.name} at ${lead.company}.

      Context:
      - Stage: ${lead.stage}
      - Interests: ${lead.interests.join(', ')}

      Email should:
      - Reference their interests
      - Provide relevant resources
      - Include a soft call-to-action
      - Sound natural and helpful

      Send to ${lead.email}.`,
    mode: "base"
  });

  return result;
}

3. Report Distribution

Automatically send periodic reports:
async function sendWeeklyReport() {
  // Generate report
  const metrics = await getWeeklyMetrics();

  const result = await agentbase.runAgent({
    message: `Create and send a weekly report email to [email protected]:

      Subject: Weekly Performance Report - ${new Date().toLocaleDateString()}

      Include:
      - Executive summary
      - Key metrics: ${JSON.stringify(metrics)}
      - Charts showing trends
      - Top achievements
      - Areas for improvement

      Make it visually appealing with HTML formatting.`,
    mode: "base"
  });

  return result;
}

// Schedule weekly
cron.schedule('0 9 * * MON', sendWeeklyReport);

4. Email-Based Workflows

Trigger actions based on incoming emails:
async function processWorkflowEmails() {
  const result = await agentbase.runAgent({
    message: `Check [email protected] for new emails and process:

      If subject contains "APPROVE":
        - Extract approval details
        - Update database
        - Send confirmation email

      If subject contains "REJECT":
        - Log rejection
        - Notify requestor

      If subject contains "URGENT":
        - Send SMS alert to on-call team
        - Create high-priority ticket`,
    mode: "base"
  });

  return result.content;
}

5. Newsletter Management

Send personalized newsletters:
interface Subscriber {
  email: string;
  name: string;
  preferences: string[];
  engagement: number;
}

async function sendNewsletter(subscribers: Subscriber[], content: any) {
  for (const subscriber of subscribers) {
    const result = await agentbase.runAgent({
      message: `Send personalized newsletter to ${subscriber.email}:

        Hi ${subscriber.name},

        Customize this content based on their preferences: ${subscriber.preferences.join(', ')}

        Base content: ${JSON.stringify(content)}

        Include:
        - Personalized greeting
        - Content matching preferences
        - Recommended articles
        - Unsubscribe link`,
      mode: "base"
    });

    // Rate limit
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

6. Order Confirmations

Send transactional emails:
interface Order {
  id: string;
  customerEmail: string;
  customerName: string;
  items: Array<{ name: string; price: number; quantity: number }>;
  total: number;
  deliveryDate: string;
}

async function sendOrderConfirmation(order: Order) {
  const result = await agentbase.runAgent({
    message: `Send order confirmation email to ${order.customerEmail}:

      Subject: Order Confirmation #${order.id}

      Hi ${order.customerName},

      Your order has been confirmed!

      Order Details:
      ${order.items.map(item =>
        `${item.quantity}x ${item.name} - $${item.price}`
      ).join('\n')}

      Total: $${order.total}
      Expected Delivery: ${order.deliveryDate}

      Include:
      - Professional HTML formatting
      - Order tracking link
      - Customer support contact
      - Thank you message`,
    mode: "base"
  });

  return result;
}

Best Practices

Personalize emails for better engagement:
// ✅ Good: Personalized
const result = await agentbase.runAgent({
  message: `Send email to ${user.email}:
    Hi ${user.name},
    Based on your interest in ${user.interests[0]}, ...`,
  mode: "base"
});

// ❌ Bad: Generic
const result = await agentbase.runAgent({
  message: "Send email to all users: Dear Customer, ...",
  mode: "base"
});
Validate email addresses before sending:
function isValidEmail(email: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

async function sendSafeEmail(to: string, content: string) {
  if (!isValidEmail(to)) {
    throw new Error(`Invalid email address: ${to}`);
  }

  return await agentbase.runAgent({
    message: `Send email to ${to}: ${content}`,
    mode: "base"
  });
}
Handle email failures gracefully:
async function sendWithRetry(email: string, content: string, maxRetries: number = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const result = await agentbase.runAgent({
        message: `Send email to ${email}: ${content}`,
        mode: "base"
      });

      return result;

    } catch (error) {
      console.error(`Attempt ${attempt + 1} failed:`, error);

      if (attempt === maxRetries - 1) {
        // Log failed email for manual review
        await logFailedEmail({ email, content, error });
        throw error;
      }

      // Wait before retry
      await new Promise(resolve =>
        setTimeout(resolve, 1000 * Math.pow(2, attempt))
      );
    }
  }
}
Respect email sending limits:
import { RateLimiter } from 'limiter';

// 10 emails per second max
const limiter = new RateLimiter({
  tokensPerInterval: 10,
  interval: 'second'
});

async function sendRateLimited(emails: string[], content: string) {
  for (const email of emails) {
    await limiter.removeTokens(1);

    await agentbase.runAgent({
      message: `Send email to ${email}: ${content}`,
      mode: "base"
    });
  }
}
Monitor email performance:
interface EmailMetrics {
  sent: number;
  delivered: number;
  opened: number;
  clicked: number;
  bounced: number;
}

async function trackEmailMetrics(campaignId: string): Promise<EmailMetrics> {
  // Track opens, clicks, bounces
  // Use email service provider's analytics API

  return {
    sent: 1000,
    delivered: 980,
    opened: 450,
    clicked: 120,
    bounced: 20
  };
}

Integration with Other Primitives

Performance Considerations

Batch Sending

Send multiple emails in batches:
// Process in batches of 100
const batches = chunk(emails, 100);

Async Processing

Use background tasks for large sends

Template Caching

Cache email templates for reuse

Queue Management

Use queues for high-volume sending

Troubleshooting

Problem: Emails fail to sendSolutions:
  • Verify SMTP/API credentials
  • Check email service provider limits
  • Validate recipient email addresses
  • Review bounce and error logs
  • Check spam filters
Problem: Emails marked as spamSolutions:
  • Set up SPF, DKIM, DMARC records
  • Use reputable email service provider
  • Avoid spam trigger words
  • Include unsubscribe link
  • Maintain good sender reputation
Problem: Email sending is slowSolutions:
  • Use batch processing
  • Implement async sending
  • Use email service provider’s bulk API
  • Optimize email content size

Next Steps