# Mail Rules Management Guide

## Overview

Mail rules (also known as Outlook Rules or filters) allow you to automatically organize incoming emails based on specific conditions. The Exchange MCP now provides comprehensive tools to create, modify, and manage these rules programmatically.

## Available Tools

### 1. `create_mail_rule` - Create New Rules
### 2. `list_mail_rules` - View Existing Rules  
### 3. `modify_mail_rule` - Update Rules
### 4. `delete_mail_rule` - Remove Rules

## Rule Components

### Conditions (When to Apply)
Rules are triggered when emails meet specified conditions:

- **From addresses**: Emails from specific senders
- **Subject contains**: Keywords in the subject line
- **Body contains**: Keywords in the email body
- **To/CC me**: Emails addressed to or copying you
- **Sent to**: Emails sent to specific addresses
- **Importance**: High, normal, or low priority emails
- **Has attachments**: Emails with file attachments

### Actions (What to Do)
When conditions are met, rules can perform these actions:

- **Move to folder**: Automatically file emails
- **Copy to folder**: Keep copy in another folder
- **Add categories**: Tag with labels/categories
- **Mark as read**: Skip inbox notifications
- **Set importance**: Change priority level
- **Forward to**: Send copy to another address
- **Delete**: Remove the email permanently
- **Stop processing**: Prevent other rules from running

## Usage Examples

### Example 1: Auto-organize Client Emails

```bash
# Create folder first
create_folder --user_id "user@example.com" --folder_name "Client Communications"

# Create rule to move client emails
create_mail_rule \
  --user_id "user@example.com" \
  --rule_name "Client Emails" \
  --conditions '{
    "from_addresses": ["client@company.com", "support@clientsite.com"],
    "subject_contains": ["PROJECT-", "CLIENT-"]
  }' \
  --actions '{
    "move_to_folder": "client-folder-id",
    "add_categories": ["Client", "Business"],
    "mark_importance": "high"
  }'
```

### Example 2: Newsletter Management

```bash
create_mail_rule \
  --user_id "user@example.com" \
  --rule_name "Newsletter Auto-Archive" \
  --conditions '{
    "subject_contains": ["newsletter", "unsubscribe", "weekly digest"],
    "to_me": false
  }' \
  --actions '{
    "move_to_folder": "newsletters-folder-id",
    "mark_as_read": true,
    "add_categories": ["Newsletter"]
  }'
```

### Example 3: High Priority Alerts

```bash
create_mail_rule \
  --user_id "user@example.com" \
  --rule_name "Urgent Alerts" \
  --conditions '{
    "subject_contains": ["URGENT", "CRITICAL", "ALERT"],
    "importance": "high"
  }' \
  --actions '{
    "add_categories": ["Urgent"],
    "mark_importance": "high",
    "stop_processing": false
  }' \
  --sequence 1
```

### Example 4: Spam/Promotional Filter

```bash
create_mail_rule \
  --user_id "user@example.com" \
  --rule_name "Marketing Filter" \
  --conditions '{
    "subject_contains": ["sale", "promotion", "discount", "limited time"],
    "body_contains": ["unsubscribe", "marketing"]
  }' \
  --actions '{
    "move_to_folder": "promotions-folder-id",
    "mark_as_read": true,
    "add_categories": ["Marketing"]
  }'
```

## Rule Management

### List All Rules
```bash
# Show only enabled rules
list_mail_rules --user_id "user@example.com"

# Show all rules including disabled ones
list_mail_rules --user_id "user@example.com" --include_disabled true
```

### Modify Existing Rules
```bash
# Disable a rule temporarily
modify_mail_rule \
  --user_id "user@example.com" \
  --rule_id "rule-id" \
  --enabled false

# Update rule conditions
modify_mail_rule \
  --user_id "user@example.com" \
  --rule_id "rule-id" \
  --conditions '{
    "from_addresses": ["new@email.com"],
    "subject_contains": ["UPDATED"]
  }'

# Change rule priority
modify_mail_rule \
  --user_id "user@example.com" \
  --rule_id "rule-id" \
  --sequence 1
```

### Delete Rules
```bash
# Requires confirmation for safety
delete_mail_rule \
  --user_id "user@example.com" \
  --rule_id "rule-id" \
  --confirm true
```

## Advanced Rule Patterns

### Multi-condition Rules
```bash
create_mail_rule \
  --user_id "user@example.com" \
  --rule_name "Complex Filter" \
  --conditions '{
    "from_addresses": ["automated@service.com"],
    "subject_contains": ["Report"],
    "has_attachments": true,
    "importance": "normal"
  }' \
  --actions '{
    "move_to_folder": "reports-folder-id",
    "add_categories": ["Reports", "Automated"]
  }'
```

### Rule Chains (Multiple Actions)
```bash
create_mail_rule \
  --user_id "user@example.com" \
  --rule_name "VIP Processing" \
  --conditions '{
    "from_addresses": ["vip@client.com", "ceo@company.com"]
  }' \
  --actions '{
    "copy_to_folder": "vip-folder-id",
    "add_categories": ["VIP", "Important"],
    "mark_importance": "high",
    "forward_to": "assistant@company.com",
    "stop_processing": false
  }'
```

### Conditional Forwarding
```bash
create_mail_rule \
  --user_id "user@example.com" \
  --rule_name "Emergency Escalation" \
  --conditions '{
    "subject_contains": ["EMERGENCY", "OUTAGE", "DOWN"],
    "importance": "high"
  }' \
  --actions '{
    "forward_to": "oncall@company.com",
    "add_categories": ["Emergency"],
    "mark_importance": "high"
  }'
```

## Best Practices

### 🎯 Rule Design Strategy

1. **Start Simple**
   - Begin with basic conditions
   - Test with a few emails first
   - Gradually add complexity

2. **Use Sequence Wisely**
   - Lower numbers = higher priority
   - Critical rules should run first
   - Use gaps (1, 5, 10) for future insertions

3. **Test Thoroughly**
   - Create rules as disabled initially
   - Test with sample emails
   - Enable after validation

### 📋 Organization Patterns

#### Priority-Based Organization
```bash
# Sequence 1: VIP emails
create_mail_rule --sequence 1 --rule_name "VIP Clients"

# Sequence 5: Project emails  
create_mail_rule --sequence 5 --rule_name "Projects"

# Sequence 10: General filing
create_mail_rule --sequence 10 --rule_name "General Organization"

# Sequence 20: Cleanup rules
create_mail_rule --sequence 20 --rule_name "Promotional Cleanup"
```

#### Content-Based Filtering
```bash
# Financial emails
create_mail_rule \
  --conditions '{"subject_contains": ["invoice", "receipt", "payment"]}' \
  --actions '{"move_to_folder": "financial-folder-id"}'

# Project communications
create_mail_rule \
  --conditions '{"subject_contains": ["PROJECT-", "[PROJ]"]}' \
  --actions '{"add_categories": ["Project"]}'
```

### ⚠️ Common Pitfalls

1. **Over-Complex Conditions**
   - Too many conditions can miss emails
   - Start broad, then narrow down

2. **Rule Order Issues**
   - Rules with `stop_processing: true` block later rules
   - Plan your sequence carefully

3. **Folder Dependencies**
   - Create folders before referencing in rules
   - Use `list_folders` to get correct folder IDs

4. **Testing Gaps**
   - Always test rules with real emails
   - Check rule execution order

## Integration with Other Tools

### Folder + Rule Setup Workflow
```bash
# 1. Set up folder structure
setup_organization_folders --user_id "user@example.com" --folder_set "business"

# 2. Get folder IDs
list_folders --user_id "user@example.com"

# 3. Create rules using folder IDs
create_mail_rule \
  --conditions '{"from_addresses": ["client@company.com"]}' \
  --actions '{"move_to_folder": "clients-folder-id"}'
```

### Category + Rule Combination
```bash
# Create rule that adds categories
create_mail_rule \
  --actions '{"add_categories": ["Project", "High Priority"]}'

# Later, search by categories
query_emails --user_id "user@example.com" --search "category:Project"
```

## Troubleshooting

### Common Issues

1. **Rule Not Working**
   - Check if rule is enabled
   - Verify condition syntax
   - Check rule sequence order

2. **Emails Missing**
   - Rule might be too restrictive
   - Check for conflicting rules
   - Verify folder IDs are correct

3. **Duplicate Processing**
   - Multiple rules matching same email
   - Use `stop_processing: true` appropriately

### Debugging Commands
```bash
# Check rule status
list_mail_rules --user_id "user@example.com" --include_disabled true

# Test rule modification
modify_mail_rule --rule_id "rule-id" --enabled false  # Disable
modify_mail_rule --rule_id "rule-id" --enabled true   # Re-enable

# Verify folder structure
list_folders --user_id "user@example.com"
```

## Response Formats

### Rule Creation Response
```json
{
  "success": true,
  "rule": {
    "id": "AAMkAGVm...",
    "displayName": "Client Emails",
    "sequence": 1,
    "isEnabled": true,
    "conditions": {
      "fromAddresses": [{"emailAddress": {"address": "client@company.com"}}]
    },
    "actions": {
      "moveToFolder": "folder-id-here",
      "assignCategories": ["Client"]
    }
  },
  "usage_tips": [
    "Test the rule with a few emails before enabling for all mail",
    "Use lower sequence numbers for higher priority rules"
  ]
}
```

### Rules List Response
```json
{
  "summary": {
    "totalRules": 5,
    "enabledRules": 4,
    "disabledRules": 1
  },
  "rules": [
    {
      "id": "rule-id",
      "displayName": "VIP Clients",
      "sequence": 1,
      "isEnabled": true,
      "hasConditions": true,
      "hasActions": true
    }
  ]
}
```

## Conclusion

Mail rules provide powerful automation for email management:

✅ **Automatic Organization** - File emails without manual intervention
✅ **Consistent Processing** - Apply same logic to all matching emails  
✅ **Time Saving** - Reduce manual email sorting
✅ **Flexible Conditions** - Match on multiple criteria
✅ **Comprehensive Actions** - Move, categorize, forward, and more

Use these tools to create a sophisticated, automated email management system that scales with your needs!