Lý thuyết
35 phút
Bài 2/3

AI-Powered Email Automation

Tự động hóa email với AI - classification, drafting, summarization

📧 AI-Powered Email Automation

Email là một trong những use cases phổ biến nhất cho AI automation. Bài này cover từ classification đến auto-reply.

Email AI Use Cases

Diagram
graph TD
    E[Incoming Email] --> C[Classify]
    C --> |Support| S[Auto-respond]
    C --> |Sales| CRM[Add to CRM]
    C --> |Spam| D[Delete/Archive]
    C --> |Important| N[Notify + Summarize]

1. Email Classification

Setup Gmail Trigger

Diagram
graph LR
    G[Gmail Trigger] --> P[Parse Email]
    P --> AI[OpenAI: Classify]
    AI --> R[Route by Category]

Gmail Trigger Configuration:

  • Trigger: On new email
  • Filters: Can filter by sender, subject, labels

OpenAI Classification:

JavaScript
1// System prompt
2const systemPrompt = `
3You are an email classifier. Classify incoming emails into one of these categories:
4- SUPPORT: Customer questions, issues, complaints
5- SALES: Inquiries about products/services, pricing
6- SPAM: Unwanted promotional, suspicious emails
7- IMPORTANT: Urgent business matters, from VIP contacts
8- GENERAL: Everything else
9
10Respond with JSON: {"category": "CATEGORY", "confidence": 0.0-1.0, "reason": "brief explanation"}
11`;
12
13// User prompt
14const userPrompt = `
15From: ${email.from}
16Subject: ${email.subject}
17Body: ${email.body.substring(0, 500)}
18`;

Parse Response:

JavaScript
1const response = $input.first().json.message.content;
2const classification = JSON.parse(response);
3
4return [{
5 json: {
6 ...email,
7 classification: classification.category,
8 confidence: classification.confidence,
9 classificationReason: classification.reason
10 }
11}];

Switch Node Routing

JavaScript
1// Route based on classification
2Switch on: {{ $json.classification }}
3
4Cases:
5- SUPPORT Support workflow
6- SALES Sales workflow
7- SPAM Delete workflow
8- IMPORTANT Urgent workflow
9- Default General inbox

2. Auto-Reply Generation

Support Email Auto-Reply

Diagram
graph LR
    E[Support Email] --> K[Search Knowledge Base]
    K --> AI[Generate Reply]
    AI --> R[Review/Send]

Knowledge Base Search:

JavaScript
1// Search relevant articles
2const query = `${email.subject} ${email.body}`;
3const results = await searchKnowledgeBase(query);
4
5return [{
6 json: {
7 email,
8 relevantArticles: results.slice(0, 3)
9 }
10}];

Generate Reply:

JavaScript
1const systemPrompt = `
2You are a customer support agent for TechStore Vietnam.
3
4Guidelines:
5- Be polite, professional, and helpful
6- Use Vietnamese if the customer writes in Vietnamese
7- Reference knowledge base articles when relevant
8- If cannot help, offer to escalate to human agent
9- Sign off with your name: "AI Assistant, TechStore Support"
10`;
11
12const userPrompt = `
13Customer Email:
14From: ${email.from}
15Subject: ${email.subject}
16Body: ${email.body}
17
18Relevant Knowledge Base Articles:
19${relevantArticles.map(a => `- ${a.title}: ${a.summary}`).join('\n')}
20
21Generate a helpful reply email.
22`;

Draft Review Workflow

JavaScript
1// Instead of auto-sending, create draft for review
2// Gmail Node: Create Draft
3To: {{ $json.email.from }}
4Subject: Re: {{ $json.email.subject }}
5Body: {{ $json.generatedReply }}
6
7// Add label for review
8Labels: ["AI-Drafted", "Needs-Review"]

3. Email Summarization

Long Email → Key Points

JavaScript
1const systemPrompt = `
2Summarize this email thread concisely. Extract:
31. Main topic (1 line)
42. Key points (bullet points)
53. Action items (if any)
64. Urgency level (Low/Medium/High)
7
8Format as structured JSON.
9`;
10
11// Input: Long email thread
12// Output:
13{
14 "topic": "Q4 Budget Approval Request",
15 "keyPoints": [
16 "Marketing requesting $50K additional budget",
17 "CFO needs approval by Friday",
18 "Finance team raised concerns about ROI"
19 ],
20 "actionItems": [
21 "Review attached spreadsheet",
22 "Schedule meeting with marketing"
23 ],
24 "urgency": "High"
25}

Daily Email Digest

Diagram
graph TD
    S[Schedule: 6PM Daily] --> G[Get Today's Emails]
    G --> F[Filter Important]
    F --> Sum[Summarize Each]
    Sum --> C[Compile Digest]
    C --> Send[Send to User]
JavaScript
1// Compile digest
2const digest = emails.map(e => `
3**${e.from}**: ${e.subject}
4${e.summary}
5Priority: ${e.urgency}
6---
7`).join('\n');
8
9// Send digest email
10Subject: "📬 Your Email Digest - {{ $now.format('MMM D') }}"
11Body: `
12# Today's Email Summary
13
14${emails.length} important emails received.
15
16${digest}
17
18---
19Generated by AI Email Assistant
20`;

4. Email Sentiment Analysis

JavaScript
1const systemPrompt = `
2Analyze the sentiment of this customer email:
3- Overall sentiment: Positive/Neutral/Negative
4- Intensity: 1-5 (1=mild, 5=intense)
5- Key emotions detected: [array]
6- Requires immediate attention: true/false
7
8Respond in JSON.
9`;
10
11// Use for:
12// - Prioritizing urgent/angry customers
13// - Flagging potential churn risks
14// - Routing to appropriate team

Complete Workflow Example

Customer Support Automation

JavaScript
1// 1. Gmail Trigger - New email to support@company.com
2
3// 2. Classify Email
4// OpenAI: Classify into category + sentiment
5
6// 3. IF: Sentiment is Negative
7// → Priority handling
8
9// 4. Search Knowledge Base
10// Vector search for relevant articles
11
12// 5. Generate Response
13// OpenAI with context from KB
14
15// 6. IF: Confidence > 0.8
16// → Auto-send reply
17// ELSE → Create draft for review
18
19// 7. Log to CRM
20// Create/update contact record
21
22// 8. Notify Team (if needed)
23// Slack message for urgent cases

Full Workflow in n8n:

Text
1Gmail Trigger
2
3Set: Parse Email Data
4
5OpenAI: Classify + Sentiment
6
7IF: Needs Human?
8 ├─ Yes → Slack: Notify Team
9 │ └─ Gmail: Create Draft
10 └─ No → HTTP: Search KB
11
12 OpenAI: Generate Reply
13
14 Gmail: Send Reply
15
16 Airtable: Log Interaction

Best Practices

Email AI Tips
  1. Never auto-send without review initially - build trust first
  2. Include opt-out for auto-replies
  3. Log everything for quality improvement
  4. Handle edge cases - out of office, forwards
  5. Test với real emails before production
  6. Monitor satisfaction - track reply quality

Bài tập thực hành

Hands-on Exercise

Build Email Support System:

  1. Gmail trigger for support emails
  2. Classification (Support/Sales/Spam)
  3. Sentiment analysis
  4. Knowledge base search (mock data)
  5. Generate draft replies
  6. Log to spreadsheet

Target: 80%+ emails auto-classified correctly


Tiếp theo

Bài tiếp theo: Content Generation Workflows - Automated content creation.