📧 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 prompt2const systemPrompt = `3You are an email classifier. Classify incoming emails into one of these categories:4- SUPPORT: Customer questions, issues, complaints5- SALES: Inquiries about products/services, pricing6- SPAM: Unwanted promotional, suspicious emails7- IMPORTANT: Urgent business matters, from VIP contacts8- GENERAL: Everything else910Respond with JSON: {"category": "CATEGORY", "confidence": 0.0-1.0, "reason": "brief explanation"}11`;1213// User prompt14const 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);34return [{5 json: {6 ...email,7 classification: classification.category,8 confidence: classification.confidence,9 classificationReason: classification.reason10 }11}];Switch Node Routing
JavaScript
1// Route based on classification2Switch on: {{ $json.classification }}34Cases:5- SUPPORT → Support workflow6- SALES → Sales workflow 7- SPAM → Delete workflow8- IMPORTANT → Urgent workflow9- Default → General inbox2. 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 articles2const query = `${email.subject} ${email.body}`;3const results = await searchKnowledgeBase(query);45return [{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.34Guidelines:5- Be polite, professional, and helpful6- Use Vietnamese if the customer writes in Vietnamese7- Reference knowledge base articles when relevant8- If cannot help, offer to escalate to human agent9- Sign off with your name: "AI Assistant, TechStore Support"10`;1112const userPrompt = `13Customer Email:14From: ${email.from}15Subject: ${email.subject}16Body: ${email.body}1718Relevant Knowledge Base Articles:19${relevantArticles.map(a => `- ${a.title}: ${a.summary}`).join('\n')}2021Generate a helpful reply email.22`;Draft Review Workflow
JavaScript
1// Instead of auto-sending, create draft for review2// Gmail Node: Create Draft3To: {{ $json.email.from }}4Subject: Re: {{ $json.email.subject }}5Body: {{ $json.generatedReply }}67// Add label for review8Labels: ["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)78Format as structured JSON.9`;1011// Input: Long email thread12// 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 digest2const digest = emails.map(e => `3**${e.from}**: ${e.subject}4${e.summary}5Priority: ${e.urgency}6---7`).join('\n');89// Send digest email10Subject: "📬 Your Email Digest - {{ $now.format('MMM D') }}"11Body: `12# Today's Email Summary1314${emails.length} important emails received.1516${digest}1718---19Generated by AI Email Assistant20`;4. Email Sentiment Analysis
JavaScript
1const systemPrompt = `2Analyze the sentiment of this customer email:3- Overall sentiment: Positive/Neutral/Negative4- Intensity: 1-5 (1=mild, 5=intense)5- Key emotions detected: [array]6- Requires immediate attention: true/false78Respond in JSON.9`;1011// Use for:12// - Prioritizing urgent/angry customers13// - Flagging potential churn risks14// - Routing to appropriate teamComplete Workflow Example
Customer Support Automation
JavaScript
1// 1. Gmail Trigger - New email to support@company.com23// 2. Classify Email4// OpenAI: Classify into category + sentiment56// 3. IF: Sentiment is Negative7// → Priority handling89// 4. Search Knowledge Base10// Vector search for relevant articles1112// 5. Generate Response13// OpenAI with context from KB1415// 6. IF: Confidence > 0.816// → Auto-send reply17// ELSE → Create draft for review1819// 7. Log to CRM20// Create/update contact record2122// 8. Notify Team (if needed)23// Slack message for urgent casesFull Workflow in n8n:
Text
1Gmail Trigger2 ↓3Set: Parse Email Data4 ↓5OpenAI: Classify + Sentiment6 ↓7IF: Needs Human?8 ├─ Yes → Slack: Notify Team9 │ └─ Gmail: Create Draft10 └─ No → HTTP: Search KB11 ↓12 OpenAI: Generate Reply13 ↓14 Gmail: Send Reply15 ↓16 Airtable: Log InteractionBest Practices
Email AI Tips
- Never auto-send without review initially - build trust first
- Include opt-out for auto-replies
- Log everything for quality improvement
- Handle edge cases - out of office, forwards
- Test với real emails before production
- Monitor satisfaction - track reply quality
Bài tập thực hành
Hands-on Exercise
Build Email Support System:
- Gmail trigger for support emails
- Classification (Support/Sales/Spam)
- Sentiment analysis
- Knowledge base search (mock data)
- Generate draft replies
- Log to spreadsheet
Target: 80%+ emails auto-classified correctly
Tiếp theo
Bài tiếp theo: Content Generation Workflows - Automated content creation.
