Google Workspace Integration
Google Workspace là nền tảng productivity phổ biến nhất. Học cách tự động hóa Google Sheets, Gmail, Drive sẽ unlock rất nhiều use cases.
🎯 Mục tiêu
- Setup Google credentials trong n8n
- Automate Google Sheets operations
- Build Gmail automation workflows
- Integrate Drive và Calendar
1. Setup Google Credentials
1.1. Tạo Google Cloud Project
- Truy cập Google Cloud Console
- Create new project: "n8n-automation"
- Enable APIs:
- Google Sheets API
- Gmail API
- Google Drive API
- Google Calendar API
1.2. Create OAuth Credentials
1Google Cloud Console2 │3 ├── APIs & Services → Credentials4 │5 ├── Create Credentials → OAuth Client ID6 │7 ├── Application type: Web application8 │9 ├── Authorized redirect URIs:10 │ https://your-n8n.com/rest/oauth2-credential/callback11 │ (hoặc http://localhost:5678/rest/oauth2-credential/callback)12 │13 └── Copy Client ID và Client Secret1.3. Add to n8n
- n8n → Credentials → Add Credential
- Search "Google Sheets OAuth2"
- Paste Client ID & Secret
- Click "Sign in with Google"
- Authorize access
2. Google Sheets Automation
2.1. Common Operations
| Operation | Use case |
|---|---|
| Append Row | Add new data |
| Read Rows | Get data |
| Update Row | Modify existing |
| Delete Row | Remove data |
| Lookup | Find specific row |
2.2. Workflow: Form to Sheet
Khi có Google Form submission → Save to master Sheet với timestamp.
1┌──────────────┐ ┌──────────────┐ ┌──────────────┐2│ Google Forms │────►│ Set Node │────►│Google Sheets │3│ Trigger │ │(Add timestamp)│ │(Append Row) │4└──────────────┘ └──────────────┘ └──────────────┘Step 1: Google Forms Trigger
1Trigger: On form submit2Form ID: [your form ID]Step 2: Set Node
1// Add processing timestamp2Fields:3- submitted_at: {{ $now.format('YYYY-MM-DD HH:mm:ss') }}4- processed: true5- source: "Google Forms"67// Keep original data8- name: {{ $json.responses.name }}9- email: {{ $json.responses.email }}Step 3: Google Sheets
1Operation: Append Row2Spreadsheet: Master Data3Sheet: Responses4Columns:5 - Name: {{ $json.name }}6 - Email: {{ $json.email }}7 - Submitted At: {{ $json.submitted_at }}2.3. Workflow: Daily Report from Sheet
Mỗi sáng đọc sales data và gửi summary.
1┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐2│ Schedule │────►│Google Sheets │────►│ Code Node │────►│ Slack │3│ (9 AM daily)│ │ (Read rows) │ │(Calculate) │ │(Send report) │4└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘Code Node (Calculate Summary):
1const items = $input.all();23// Calculate totals4const totalSales = items.reduce((sum, item) => 5 sum + parseFloat(item.json.amount || 0), 0);67const totalOrders = items.length;8const avgOrder = totalSales / totalOrders;910// Find top product11const productCounts = {};12items.forEach(item => {13 const product = item.json.product;14 productCounts[product] = (productCounts[product] || 0) + 1;15});16const topProduct = Object.keys(productCounts)17 .reduce((a, b) => productCounts[a] > productCounts[b] ? a : b);1819return [{20 json: {21 report_date: new Date().toISOString().split('T')[0],22 total_sales: totalSales.toFixed(2),23 total_orders: totalOrders,24 avg_order: avgOrder.toFixed(2),25 top_product: topProduct,26 message: `📊 Daily Sales Report27 28�� Total Sales: $${totalSales.toFixed(2)}29�� Orders: ${totalOrders}30�� Avg Order: $${avgOrder.toFixed(2)}31�� Top Product: ${topProduct}`32 }33}];2.4. Advanced: Lookup và Update
1Workflow: Update order status2 3Trigger: Webhook (order shipped notification)4 │5 ├── Google Sheets: Lookup (find by Order ID)6 │7 ├── IF: Row found?8 │ ├── Yes → Google Sheets: Update Row (status = "Shipped")9 │ └── No → Slack: Alert "Order not found"10 │11 └── Email: Send tracking to customer3. Gmail Automation
3.1. Gmail Trigger
1Trigger when:2- New email received3- Email with specific label4- Email from specific sender5- Email with attachment3.2. Workflow: Invoice Processing
Email invoice → Extract data → Save to Sheet → Archive email
1┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐2│Gmail Trigger │────►│ Code Node │────►│Google Sheets │────►│ Gmail │3│(Label:Invoice)│ │(Extract data)│ │(Append row) │ │(Add label) │4└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘Gmail Trigger Config:
1Trigger: On new email2Filters:3 - Label: Invoices4 - Has Attachment: trueCode Node (Extract Invoice Data):
1const email = $input.first().json;23// Simple extraction from subject/body4const subject = email.subject;5const body = email.text;67// Extract invoice number (assuming format: INV-XXXXX)8const invoiceMatch = body.match(/INV-\d+/);9const invoiceNumber = invoiceMatch ? invoiceMatch[0] : 'Unknown';1011// Extract amount (assuming format: $X,XXX.XX)12const amountMatch = body.match(/\$[\d,]+\.?\d*/);13const amount = amountMatch ? amountMatch[0].replace(/[$,]/g, '') : '0';1415// Extract date16const dateMatch = body.match(/\d{1,2}\/\d{1,2}\/\d{4}/);17const invoiceDate = dateMatch ? dateMatch[0] : new Date().toLocaleDateString();1819return [{20 json: {21 invoice_number: invoiceNumber,22 amount: parseFloat(amount),23 date: invoiceDate,24 from: email.from,25 subject: subject,26 received_at: new Date().toISOString()27 }28}];3.3. Send Emails
1Workflow: Weekly newsletter2 3Schedule (Monday 9 AM)4 │5 ├── Google Sheets: Get subscribers6 │7 ├── Split In Batches (10 per batch)8 │9 └── Gmail: Send email10 - To: {{ $json.email }}11 - Subject: Weekly Update12 - Body: [HTML template]Gmail Node Config:
1Operation: Send Email2To: {{ $json.email }}3Subject: 📬 Weekly Newsletter - {{ $now.format('MMMM D') }}4Email Type: HTML5Body:1<div style="font-family: Arial; max-width: 600px; margin: 0 auto;">2 <h1>Hello {{ $json.name }}!</h1>3 <p>Here's your weekly update...</p>4 <a href="https://example.com" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">5 Read More6 </a>7</div>4. Google Drive Integration
4.1. Common Operations
| Operation | Description |
|---|---|
| Upload | Add files to Drive |
| Download | Get files from Drive |
| Create Folder | Organize files |
| Move | Reorganize files |
| Share | Set permissions |
4.2. Workflow: Auto-backup Attachments
Email với attachment → Save to Drive → Log to Sheet
1┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐2│Gmail Trigger │────►│Google Drive │────►│Google Sheets │────►│ Gmail │3│(Has attach) │ │(Upload file) │ │(Log details) │ │(Send confirm)│4└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘Google Drive Upload Config:
1Operation: Upload2File Name: {{ $json.attachments[0].filename }}3Parent Folder: [Backup Folder ID]4Binary Property: data (from Gmail attachment)4.3. Generate and Upload Reports
1Schedule2 │3 ├── HTTP Request: Get data from API4 │5 ├── Code: Generate CSV content6 │7 ├── Google Drive: Upload as CSV8 │9 └── Gmail: Send link to team5. Google Calendar
5.1. Workflow: Meeting Reminder
Sáng mỗi ngày check calendar và gửi summary.
1┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐2│ Schedule │────►│ Calendar │────►│ Code Node │────►│ Slack │3│ (7:30 AM) │ │(Get today's) │ │(Format list) │ │(Post agenda) │4└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘Google Calendar Config:
1Operation: Get Many2Calendar: Primary3Time Min: {{ $now.startOf('day').toISO() }}4Time Max: {{ $now.endOf('day').toISO() }}Format Code:
1const events = $input.all();23if (events.length === 0) {4 return [{5 json: {6 message: "📅 No meetings today! Time for deep work. 💪"7 }8 }];9}1011const eventList = events.map(e => {12 const start = new Date(e.json.start.dateTime || e.json.start.date);13 const time = start.toLocaleTimeString('en-US', { 14 hour: '2-digit', 15 minute: '2-digit' 16 });17 return `• ${time} - ${e.json.summary}`;18}).join('\n');1920return [{21 json: {22 message: `📅 Today's Schedule (${events.length} meetings)\n\n${eventList}`23 }24}];5.2. Auto-create Calendar Events
1Google Form (Meeting Request)2 │3 ├── Google Calendar: Create Event4 │5 ├── Gmail: Send confirmation6 │7 └── Google Sheets: Log request6. Complete Project: Lead Management
Full Workflow
1Google Form → Sheet → Email Sequence → CRM Update2 3┌─────────────┐4│ Google Form │5│ (New Lead) │6└──────┬──────┘7 │8 ▼9┌─────────────┐ ┌─────────────┐10│Google Sheets│────►│ Gmail │11│(Save + Score)│ │(Welcome) │12└──────┬──────┘ └─────────────┘13 │14 ▼15┌─────────────┐ ┌─────────────┐16│ Wait │────►│ Gmail │17│ (2 days) │ │(Follow-up) │18└──────┬──────┘ └─────────────┘19 │20 ▼21┌─────────────┐22│ Slack │23│(Notify sales)│24└─────────────┘Implementation Notes
- Lead Scoring (Code Node):
1const lead = $input.first().json;23let score = 0;4// Score based on company size5if (lead.company_size === 'Enterprise') score += 30;6else if (lead.company_size === 'SMB') score += 20;7else score += 10;89// Score based on urgency10if (lead.timeline === 'Immediate') score += 40;11else if (lead.timeline === '1-3 months') score += 25;12else score += 10;1314return [{15 json: {16 ...lead,17 lead_score: score,18 priority: score >= 60 ? 'High' : score >= 40 ? 'Medium' : 'Low'19 }20}];- Conditional Follow-up:
1IF lead_score >= 60:2 → Immediate sales call3 → Personal email from account exec4ELSE:5 → Nurture sequence6 → Weekly newsletter📝 Quiz
-
OAuth2 credentials cần gì từ Google Cloud?
- API Key only
- Client ID và Client Secret
- Service Account
- Username/Password
-
Google Sheets "Append Row" làm gì?
- Xóa row cuối
- Update row đầu
- Thêm row mới ở cuối
- Replace toàn bộ data
-
Gmail trigger có thể filter theo?
- Chỉ sender
- Chỉ subject
- Label, sender, attachment, và nhiều criteria khác
- Không filter được
-
Cách upload file lên Drive trong n8n?
- Paste URL
- Dùng binary data từ node trước
- Chỉ text files
- Không thể upload qua n8n
🎯 Key Takeaways
- OAuth2 setup cần làm 1 lần, dùng cho nhiều workflows
- Google Sheets = Database đơn giản cho automation
- Gmail + Drive + Calendar = Full productivity automation
- Combine services để build complex workflows
- Code nodes help extract/transform data linh hoạt
🚀 Bài tiếp theo
Error Handling và Monitoring - Học cách xử lý lỗi và monitor workflows production!
