Introduction
In this tutorial, we'll explore how to create a basic AI agent that can interact with email systems and execute commands - similar to the OpenClaw AI agent mentioned in the news article. This hands-on guide will teach you how to build a simple email automation agent using Python, with proper security considerations and safeguards. Understanding these systems is crucial as AI agents become more integrated into enterprise environments.
Prerequisites
- Basic Python knowledge
- Python 3.7 or higher installed
- Access to an email account (preferably a test account)
- Basic understanding of IMAP/SMTP protocols
- Virtual environment setup knowledge
Step-by-Step Instructions
1. Set Up Your Development Environment
First, create a virtual environment to isolate our project dependencies:
python -m venv email_agent_env
source email_agent_env/bin/activate # On Windows: email_agent_env\Scripts\activate
Why: Using a virtual environment ensures we don't pollute our global Python installation and keeps dependencies organized.
2. Install Required Libraries
Install the necessary Python packages for email handling and AI integration:
pip install imaplib2 email python-dotenv
Why: imaplib2 provides IMAP functionality for email access, email handles email parsing, and python-dotenv helps manage sensitive configuration.
3. Create Configuration File
Create a .env file in your project directory to store email credentials:
[email protected]
EMAIL_PASSWORD=your_email_password
IMAP_SERVER=imap.example.com
SMTP_SERVER=smtp.example.com
Why: Storing credentials in environment variables keeps them out of your source code, preventing accidental exposure.
4. Create the Basic Email Agent Class
Create a file called email_agent.py with the following code:
import imaplib
import email
import os
from dotenv import load_dotenv
load_dotenv()
class EmailAgent:
def __init__(self):
self.email = os.getenv('EMAIL_ADDRESS')
self.password = os.getenv('EMAIL_PASSWORD')
self.imap_server = os.getenv('IMAP_SERVER')
self.smtp_server = os.getenv('SMTP_SERVER')
self.mail = None
def connect(self):
try:
self.mail = imaplib.IMAP4_SSL(self.imap_server)
self.mail.login(self.email, self.password)
print("Connected to email server")
except Exception as e:
print(f"Connection failed: {e}")
def disconnect(self):
if self.mail:
self.mail.close()
self.mail.logout()
print("Disconnected from email server")
Why: This class structure provides a foundation for email operations while handling connection errors gracefully.
5. Add Email Reading Functionality
Add this method to your EmailAgent class:
def read_emails(self, folder='INBOX', count=5):
try:
self.mail.select(folder)
status, messages = self.mail.search(None, 'ALL')
email_ids = messages[0].split()
for email_id in email_ids[-count:]:
status, msg_data = self.mail.fetch(email_id, '(RFC822)')
msg = email.message_from_bytes(msg_data[0][1])
print(f"Subject: {msg['Subject']}")
print(f"From: {msg['From']}")
print("---")
except Exception as e:
print(f"Error reading emails: {e}")
Why: This method allows us to read recent emails, which is essential for AI agents to understand their environment before taking action.
6. Implement Safe Deletion Functionality
Now add a deletion method with safety checks:
def delete_email_safely(self, subject_keyword):
try:
self.mail.select('INBOX')
status, messages = self.mail.search(None, f'SUBJECT "{subject_keyword}"')
email_ids = messages[0].split()
if not email_ids:
print(f"No emails found with subject containing '{subject_keyword}'")
return
print(f"Found {len(email_ids)} emails to delete")
for email_id in email_ids:
# Mark for deletion (doesn't actually delete until expunge)
self.mail.store(email_id, '+FLAGS', '\Deleted')
print(f"Marked email {email_id} for deletion")
# Actually delete marked emails
self.mail.expunge()
print("Emails deleted successfully")
except Exception as e:
print(f"Error deleting email: {e}")
Why: The IMAP protocol marks emails for deletion first, then requires an explicit expunge command, which provides a safety mechanism.
7. Create a Main Execution Script
Create a main.py file to test your agent:
from email_agent import EmailAgent
def main():
agent = EmailAgent()
agent.connect()
# Read recent emails
print("Reading recent emails:")
agent.read_emails(count=3)
# Safely delete an email (use a test subject)
print("\nAttempting to delete emails:")
agent.delete_email_safely("Test Subject")
agent.disconnect()
if __name__ == "__main__":
main()
Why: This script demonstrates the complete workflow and shows how the agent would be used in practice.
8. Add Logging and Error Handling
Enhance your agent with proper logging:
import logging
# Add to your class initialization
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def delete_email_safely(self, subject_keyword):
try:
self.mail.select('INBOX')
status, messages = self.mail.search(None, f'SUBJECT "{subject_keyword}"')
email_ids = messages[0].split()
logger.info(f"Found {len(email_ids)} emails with subject '{subject_keyword}'")
if not email_ids:
logger.warning("No matching emails found")
return
for email_id in email_ids:
self.mail.store(email_id, '+FLAGS', '\Deleted')
logger.info(f"Marked email {email_id} for deletion")
self.mail.expunge()
logger.info("Emails deleted successfully")
except Exception as e:
logger.error(f"Error deleting email: {e}")
raise
Why: Proper logging helps track what the agent is doing and makes debugging easier, especially in production environments.
Summary
This tutorial demonstrated how to build a basic email agent that can read and delete emails using IMAP protocols. The key lessons include proper connection handling, safety mechanisms like the IMAP mark-and-expunge pattern, and secure credential management. While this is a simplified example, it illustrates the fundamental concepts behind AI agents that interact with email systems. The news article's example shows how such agents, when given dangerous instructions, can cause serious damage - which is why implementing safeguards and logging is crucial for any real-world AI system.
Remember: Always test AI agents in controlled environments and implement comprehensive safety mechanisms before deploying them in production systems.



