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
// Send a simple emailconst result = await agentbase.runAgent({ message: `Send an email to john@example.com with: Subject: "Project Update" Body: "The project is on track and will be completed by Friday."`, mode: "base"});
// Send personalized email with dataconst customer = { name: "Jane Smith", email: "jane@example.com", 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"});
// Send HTML formatted emailconst result = await agentbase.runAgent({ message: `Send an HTML email to team@example.com 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"});
// Send email with attachmentsconst result = await agentbase.runAgent({ message: `Send an email to client@example.com 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"});
// Process received emailsconst 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 structured data from emailsconst result = await agentbase.runAgent({ message: `Read the email from orders@supplier.com and extract: - Order number - Items ordered - Total amount - Expected delivery date Return as JSON.`, mode: "base"});const orderData = JSON.parse(result.content);
async function processCustomerEmails() { // Get unread support emails const result = await agentbase.runAgent({ message: `Check support@example.com 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 periodicallysetInterval(processCustomerEmails, 5 * 60 * 1000); // Every 5 minutes
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;}
// ✅ Good: Personalizedconst result = await agentbase.runAgent({ message: `Send email to ${user.email}: Hi ${user.name}, Based on your interest in ${user.interests[0]}, ...`, mode: "base"});// ❌ Bad: Genericconst result = await agentbase.runAgent({ message: "Send email to all users: Dear Customer, ...", mode: "base"});
Email Validation
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" });}
Error Handling
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)) ); } }}
Rate Limiting
Respect email sending limits:
import { RateLimiter } from 'limiter';// 10 emails per second maxconst 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" }); }}
Unsubscribe Links
Always include unsubscribe options:
async function sendMarketingEmail(subscriber: any, content: string) { const unsubscribeLink = `https://example.com/unsubscribe?email=${subscriber.email}`; const result = await agentbase.runAgent({ message: `Send email to ${subscriber.email}: ${content} Include unsubscribe link at bottom: ${unsubscribeLink}`, mode: "base" }); return result;}