# Email Agent Setup Guide
Complete installation and deployment instructions for the Email Agent system.
---
## Prerequisites
- Python 3.8+
- Gmail account (for test/production use)
- SendGrid account (for email sending)
- Anthropic API key (Claude API access)
---
## Step 1: Install Dependencies
```bash
cd K:\projekte-AG\email_agent
pip install -r requirements.txt
```
---
## Step 2: Gmail API Setup
### 2.1 Create Google Cloud Project
1. Go to [Google Cloud Console](https://console.cloud.google.com)
2. Create a new project: "Email Agent agentsolutions"
3. Enable APIs:
- Gmail API
- Google+ API
### 2.2 Create OAuth Credentials
1. Go to "Credentials" → "Create Credentials" → "OAuth 2.0 Client ID"
2. Choose "Desktop application"
3. Download JSON file → save as `credentials.json` in email_agent folder
### 2.3 First Authentication
```bash
python agent.py
```
First run will open browser for OAuth consent. Grant permissions and token will be saved to `token.pickle`.
---
## Step 3: SendGrid Setup
### 3.1 Create SendGrid Account
1. Go to [SendGrid](https://app.sendgrid.com)
2. Create account (free tier available)
### 3.2 Generate API Key
1. Settings → API Keys → Create API Key
2. Choose "Restricted Access"
3. Enable: Mail Send
4. Copy API key
### 3.3 Set Environment Variable
**Windows (PowerShell):**
```powershell
[System.Environment]::SetEnvironmentVariable("SENDGRID_API_KEY", "SG.your_key_here", [System.EnvironmentVariableTarget]::User)
```
Or add to `.env` file:
```
SENDGRID_API_KEY=SG.your_key_here
```
---
## Step 4: Anthropic API Setup
### 4.1 Get API Key
1. Go to [Anthropic Console](https://console.anthropic.com)
2. API Keys → Create API Key
3. Copy key
### 4.2 Set Environment Variable
**Windows (PowerShell):**
```powershell
[System.Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "sk-ant-your_key_here", [System.EnvironmentVariableTarget]::User)
```
Or add to `.env` file:
```
ANTHROPIC_API_KEY=sk-ant-your_key_here
```
---
## Step 5: Database Initialization
Database is automatically created on first run. Tables:
- `email_log` — incoming emails
- `email_templates` — response templates
- `email_queue` — outgoing emails
```bash
# Optional: Verify database
python -c "from database import EmailDatabase; db = EmailDatabase(); print(db.get_statistics())"
```
---
## Step 6: Test Setup
### 6.1 Process Test Emails
```bash
python -c "
from agent import EmailAgent
agent = EmailAgent()
results = agent.process_incoming_emails(max_results=5)
print(f'Processed {results[\"processed\"]} emails')
print(f'Auto-replied: {results[\"auto_replied\"]}')
print(f'Escalated: {results[\"escalated\"]}')
"
```
### 6.2 Send Queued Emails
```bash
python -c "
from agent import EmailAgent
agent = EmailAgent()
results = agent.send_queued_emails()
print(f'Sent: {results[\"sent\"]}, Failed: {results[\"failed\"]}')
"
```
### 6.3 Check Statistics
```bash
python -c "
from agent import EmailAgent
agent = EmailAgent()
stats = agent.get_statistics()
print(stats)
"
```
---
## Step 7: Run Continuously
### Option A: Direct Python
```bash
python agent.py
```
This will:
- Check for new emails every 60 seconds
- Send queued emails every 30 seconds
- Log all activities to console
### Option B: Windows Task Scheduler
Create scheduled task to run agent continuously:
```batch
# Create run_agent.bat
@echo off
cd K:\projekte-AG\email_agent
python agent.py
```
Then schedule via Windows Task Scheduler with:
- Trigger: At system startup
- Action: Run `run_agent.bat`
- Settings: Allow on-demand run, restart on failure
### Option C: n8n Integration
Create n8n webhook workflow:
```json
{
"name": "Email Agent Webhook",
"nodes": [
{
"name": "Webhook Trigger",
"type": "n8n-nodes-base.webhook",
"webhookId": "email-agent",
"path": "/email-agent"
},
{
"name": "Process Emails",
"type": "n8n-nodes-base.executeCommand",
"command": "python K:\\projekte-AG\\email_agent\\agent.py"
}
]
}
```
---
## Step 8: Production Deployment
### 8.1 Environment Configuration
Create `.env` file in email_agent folder:
```env
ANTHROPIC_API_KEY=sk-ant-...
SENDGRID_API_KEY=SG....
GMAIL_CREDENTIALS_FILE=credentials.json
DATABASE_PATH=email_agent.db
LOG_LEVEL=INFO
```
### 8.2 Update agent.py with env vars
```python
from dotenv import load_dotenv
load_dotenv()
agent = EmailAgent(
credentials_file=os.getenv('GMAIL_CREDENTIALS_FILE'),
sendgrid_api_key=os.getenv('SENDGRID_API_KEY'),
anthropic_api_key=os.getenv('ANTHROPIC_API_KEY'),
db_path=os.getenv('DATABASE_PATH', 'email_agent.db')
)
```
### 8.3 Monitoring & Logging
Email agent logs to:
- Console (stdout)
- Optional: Log file (add FileHandler to logging)
Monitor these metrics:
- Emails processed per hour
- Auto-reply success rate
- Escalation rate
- Response time
---
## Step 9: Configuration & Customization
### Add Custom Templates
```python
from response_templates import ResponseTemplates
ResponseTemplates.TEMPLATES['custom_category'] = {
'subject': 'Custom Subject',
'body': 'Custom response body...'
}
```
### Modify Classifier
Edit email categories in `email_classifier.py`:
```python
CATEGORIES = {
"custom_category": {
"keywords": ["your", "keywords"],
"action": "auto_reply",
"template": "custom_category"
}
}
```
### Change Check Intervals
```python
# Process emails every 30 seconds, send every 15 seconds
agent.run_continuous(check_interval=30, send_interval=15)
```
---
## Troubleshooting
### Issue: Gmail authentication fails
**Solution:**
1. Delete `token.pickle`
2. Re-run to get new token
3. Check Gmail app password if 2FA enabled
### Issue: SendGrid emails not sending
**Solution:**
1. Verify API key: `echo %SENDGRID_API_KEY%`
2. Check SendGrid account has email credits
3. Verify recipient email is valid
### Issue: Claude API errors
**Solution:**
1. Verify API key is set: `echo %ANTHROPIC_API_KEY%`
2. Check API key quota/credits
3. Verify email content is valid text (no binary)
### Issue: Database locked
**Solution:**
1. Check no other instances running
2. Delete `email_agent.db` to reset (loses history)
3. Use write-ahead logging (WAL) mode for concurrency
---
## API Costs (Estimated Monthly)
| Service | Usage | Cost |
|---------|-------|------|
| Gmail API | Unlimited (free) | €0 |
| SendGrid | 100 emails/day | €15-20 |
| Claude API | 10k emails × 2000 tokens avg | €10-20 |
| **TOTAL** | **Full email automation** | **€25-40** |
---
## Next Steps
1. ✅ Install dependencies
2. ✅ Setup Gmail API
3. ✅ Setup SendGrid
4. ✅ Setup Anthropic API
5. ✅ Test with real emails
6. ✅ Deploy to production
7. Monitor performance
8. Optimize templates based on feedback
---
## Support
For issues or questions:
- Email: support@agentsolutions.tech
- Check logs: `python agent.py | more`
- Review database: `python -c "from database import EmailDatabase; ..."`
---
**Status:** Ready for deployment ✅
**Last Updated:** 2026-04-04