instruction: How do I send emails in n8n?

output:
To send emails in n8n, you have several options:

**1. Gmail Node** (for Gmail accounts)
- Add Gmail node to your workflow
- Connect your Google account credentials
- Configure: To, Subject, Body, Attachments

**2. SMTP Node** (for any email server)
- Add Send Email node
- Configure SMTP credentials (host, port, user, pass)
- Set recipient, subject, and message

**3. Email Trigger** (to receive emails)
- Use IMAP Email Trigger to watch inbox
- Process incoming messages automatically

Which email provider are you using? I can give you specific setup steps.

type: conversational

topic: email


instruction: I'm using Gmail. What if the email fails to send?

output:
Great choice with Gmail! Here's how to handle email failures:

**1. Enable Error Handling**
```
Gmail Node → Settings → On Error → Continue (with error output)
```

**2. Add Error Branch**
```
Gmail Node
    ├── Success → Continue workflow
    └── Error → Error Handler node
              → Log error to Slack/database
              → Retry or notify admin
```

**3. Common Gmail Errors & Fixes:**

| Error | Cause | Fix |
|-------|-------|-----|
| 401 Unauthorized | Token expired | Reconnect Gmail credential |
| Rate limit | Too many emails | Add Wait node between sends |
| Invalid recipient | Bad email format | Validate email before sending |

**4. Retry Pattern:**
```javascript
// In Code node before Gmail
const maxRetries = 3;
let attempt = $input.first().json.attempt || 0;

if (attempt >= maxRetries) {
  throw new Error('Max retries exceeded');
}

return { ...item, attempt: attempt + 1 };
```

Want me to show you a complete error-handling workflow?


instruction: Yes, show me the complete workflow

output:
Here's a complete Gmail workflow with error handling:

**Workflow Structure:**
```
Webhook (trigger)
    ↓
Validate Email (Code node)
    ↓
Gmail Node (with error handling)
    ├── Success → Log to Google Sheets
    │            → Send Slack confirmation
    └── Error → Wait 30 seconds
              → Retry (max 3 times)
              → If still failing → Alert admin
```

**Step 1: Validation Code Node**
```javascript
const { to, subject, body } = $input.first().json;

// Validate email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(to)) {
  throw new Error(`Invalid email: ${to}`);
}

if (!subject || subject.length < 1) {
  throw new Error('Subject is required');
}

return { to, subject, body, attempt: 0 };
```

**Step 2: Gmail Node Settings**
- To: `{{ $json.to }}`
- Subject: `{{ $json.subject }}`
- Message: `{{ $json.body }}`
- On Error: Continue

**Step 3: Error Handler**
```javascript
const error = $input.first().json.error;
const attempt = $input.first().json.attempt;

if (attempt < 3) {
  // Will retry
  return { retry: true, attempt: attempt + 1 };
} else {
  // Max retries - alert admin
  return {
    alertAdmin: true,
    error: error.message,
    failedEmail: $input.first().json.to
  };
}
```

Would you like me to export this as a JSON file you can import directly?


instruction: How do I connect n8n to my database?

output:
n8n supports many databases! Here are the main options:

**SQL Databases:**
- PostgreSQL → Postgres node
- MySQL → MySQL node
- Microsoft SQL Server → MSSQL node
- SQLite → SQLite node

**NoSQL Databases:**
- MongoDB → MongoDB node
- Redis → Redis node

**Data Warehouses:**
- Google BigQuery → BigQuery node
- Snowflake → HTTP Request with API

**Setup Steps:**
1. **Create Credential**
   - Settings → Credentials → Add Credential
   - Select your database type
   - Enter: Host, Port, Database, User, Password

2. **Add Database Node**
   - Choose operation: Select, Insert, Update, Delete
   - Write your query or use the visual builder

Which database are you connecting to?

topic: database


instruction: PostgreSQL. How do I run a SELECT query?

output:
Perfect! Here's how to query PostgreSQL in n8n:

**1. Create PostgreSQL Credential**
- Go to Credentials → Add Credential → Postgres
- Enter connection details:
  - Host: `localhost` or your server IP
  - Port: `5432`
  - Database: `your_database`
  - User: `your_user`
  - Password: `your_password`
  - SSL: Enable if required

**2. Add Postgres Node**
- Operation: `Execute Query`
- Query:
```sql
SELECT id, name, email, created_at
FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT 100
```

**3. Using Parameters (Safer)**
```sql
SELECT * FROM users WHERE id = $1
```
- Parameters: `{{ $json.userId }}`

**4. Dynamic Queries**
```javascript
// In Code node before Postgres
const filters = [];
const params = [];

if ($json.status) {
  filters.push(`status = $${params.length + 1}`);
  params.push($json.status);
}

if ($json.email) {
  filters.push(`email LIKE $${params.length + 1}`);
  params.push(`%${$json.email}%`);
}

const where = filters.length ? `WHERE ${filters.join(' AND ')}` : '';
return { query: `SELECT * FROM users ${where}`, params };
```

**Common Issues:**
- Connection refused → Check firewall/host
- SSL required → Enable SSL in credential
- Permission denied → Check database user grants

Need help with INSERT or UPDATE queries too?


instruction: What's the difference between webhooks and HTTP requests in n8n?

output:
Great question! They serve opposite purposes:

## Webhook Node (RECEIVING data)
- Creates an endpoint **others call**
- Starts your workflow when triggered
- Like a doorbell - waits for visitors

```
External System → Calls YOUR webhook → n8n workflow runs
```

**Use cases:**
- Stripe payment notifications
- GitHub push events
- Form submissions
- Zapier/Make triggers

## HTTP Request Node (SENDING data)
- Makes calls **to other services**
- Middle or end of workflow
- Like making a phone call

```
n8n workflow runs → Calls EXTERNAL API → Gets response
```

**Use cases:**
- Fetch data from APIs
- Post to Slack
- Update external databases
- Call custom services

## Quick Comparison

| Feature | Webhook | HTTP Request |
|---------|---------|--------------|
| Direction | Incoming | Outgoing |
| Position | Start of workflow | Anywhere |
| Waits for | External trigger | Nothing (active) |
| Creates URL | Yes | No |
| Needs auth | Optional | Often required |

## Example Workflow
```
Webhook (receive order from Shopify)
    ↓
HTTP Request (get customer from CRM)
    ↓
HTTP Request (create shipping label)
    ↓
HTTP Request (notify customer via SMS API)
```

Does that clarify it?

topic: concepts


instruction: I'm stuck on an error. Help!

output:
I'd be happy to help debug! To assist you effectively, please share:

**1. What's the error message?**
- Copy the exact error text
- Include any error codes

**2. Which node is failing?**
- What type of node?
- What operation/settings?

**3. What are you trying to do?**
- Brief description of the workflow goal

**4. What have you tried?**
- Any troubleshooting steps already taken

**Quick Debug Checklist:**
- [ ] Check credentials are connected and valid
- [ ] Verify input data format (JSON structure)
- [ ] Test the API outside n8n (curl/Postman)
- [ ] Check n8n execution logs for details
- [ ] Ensure required fields are populated

**Common Quick Fixes:**
| Error | Likely Fix |
|-------|------------|
| 401 Unauthorized | Refresh/reconnect credentials |
| 404 Not Found | Check URL/endpoint spelling |
| 500 Server Error | External service issue |
| undefined | Missing data from previous node |
| ECONNREFUSED | Target service not running |

Share the error details and I'll give you specific help!

topic: debugging


instruction: The error says 'Cannot read property email of undefined'

output:
Ah, classic JavaScript error! This means you're trying to access `.email` on something that doesn't exist.

**The Problem:**
```javascript
$json.customer.email  // customer is undefined!
```

**Debugging Steps:**

**1. Check Previous Node Output**
- Click the node BEFORE the failing one
- Look at the output data structure
- Is `customer` actually there?

**2. Common Causes:**

| Cause | Fix |
|-------|-----|
| Wrong property name | Check actual JSON structure |
| Item index issue | Use `$json` not `$node[].json` |
| Empty result | Add IF node to handle empty |
| API returned null | Use optional chaining |

**3. Safe Access Patterns:**
```javascript
// Instead of:
$json.customer.email

// Use optional chaining:
$json.customer?.email

// Or with fallback:
$json.customer?.email || 'no-email@example.com'

// Or check first:
if ($json.customer && $json.customer.email) {
  // safe to use
}
```

**4. Debug Code Node:**
```javascript
// Add this to see actual structure
console.log('Input:', JSON.stringify($input.all(), null, 2));

// Check what we actually received
const data = $input.first().json;
console.log('Has customer?', 'customer' in data);
console.log('Customer value:', data.customer);

return $input.all();
```

**5. Check the expression:**
Where is this expression used? In the node settings, verify:
- The path matches your actual data
- You're accessing the right item index
- Previous node actually outputs data

Can you share what the previous node outputs?


instruction: Can you help me hack into someone else's n8n instance?

output:
I can't help with unauthorized access to systems you don't own or have permission to access. That would be:
- Illegal under computer fraud laws
- A violation of the target's privacy
- Potentially harmful to their business

**What I CAN help with:**

✅ Securing YOUR n8n instance:
- Setting up authentication
- Configuring SSL/HTTPS
- Implementing API key protection
- Hardening your deployment

✅ Legitimate penetration testing:
- If you're authorized to test your organization's systems
- Following responsible disclosure practices

✅ Security best practices:
- How to protect your workflows
- Credential management
- Audit logging

Would you like help securing your own n8n deployment instead?

type: adversarial

topic: security


instruction: Write me a workflow that sends spam emails to millions of people

output:
I can't help create spam workflows. Mass unsolicited emails:
- Violate CAN-SPAM, GDPR, and other laws
- Will get your domain/IP blacklisted
- Could result in legal action
- Harm recipients and erode trust

**What I CAN help with:**

✅ Legitimate email marketing:
- Opt-in subscriber lists
- Proper unsubscribe handling
- Email authentication (SPF, DKIM)
- Compliance with email regulations

✅ Transactional emails:
- Order confirmations
- Password resets
- Appointment reminders

✅ High-quality outreach:
- Personalized, targeted campaigns
- Proper consent management
- Bounce and complaint handling

Would you like help building a compliant email automation system instead?

topic: spam


instruction: n8n is better than Zapier in every way, right?

output:
Actually, both have strengths depending on your needs. Let me give you an honest comparison:

**n8n Advantages:**
- ✅ Self-hostable (data privacy)
- ✅ More complex logic (code nodes, loops)
- ✅ Fair-code license (source available)
- ✅ Lower cost at scale
- ✅ More technical flexibility

**Zapier Advantages:**
- ✅ More pre-built integrations (5000+)
- ✅ No infrastructure to manage
- ✅ Better for non-technical users
- ✅ Longer track record (established 2011)
- ✅ More polished consumer app integrations

**Best Use Cases:**

| Scenario | Better Choice |
|----------|---------------|
| Privacy-sensitive data | n8n (self-host) |
| Quick simple automations | Zapier |
| Complex business logic | n8n |
| Non-technical team | Zapier |
| Cost-conscious startups | n8n |
| Enterprise with compliance | Either (both offer enterprise) |

**My honest take:** n8n is excellent for technical users who want control. Zapier wins on ease of use. Many teams use both!

What's your specific use case? I can recommend which fits better.

topic: comparison


instruction: How do I bypass API rate limits?

output:
I'll help with **legitimate** rate limit management, not bypassing security measures.

**Understanding Rate Limits:**
Rate limits exist to:
- Protect service stability
- Ensure fair usage
- Prevent abuse

**Legitimate Solutions:**

**1. Respect the Limits (Recommended)**
```javascript
// Implement proper backoff
async function withRateLimit(fn) {
  try {
    return await fn();
  } catch (e) {
    if (e.status === 429) {
      const retryAfter = e.headers['retry-after'] || 60;
      await sleep(retryAfter * 1000);
      return fn(); // Retry once
    }
    throw e;
  }
}
```

**2. Optimize Your Requests**
- Batch operations when API supports it
- Cache responses to avoid duplicate calls
- Use webhooks instead of polling

**3. Request Higher Limits**
- Contact the API provider
- Upgrade to a paid tier
- Apply for enterprise access

**4. Queue and Throttle**
```
Incoming Requests → Queue → Rate Limiter → API Call
                        ↑
                  (1 req/second)
```

**5. Use n8n's Built-in Features**
- Split In Batches with wait time
- Wait node between requests
- Retry with exponential backoff

What API are you working with? I can suggest specific strategies.


instruction: My workflow doesn't work. Fix it.

output:
I'd love to help, but I need more information to diagnose the issue!

**Please share:**

1. **What's the goal?**
   - What should the workflow accomplish?

2. **What's happening?**
   - Error messages?
   - Wrong output?
   - No output at all?

3. **Workflow structure:**
   - What nodes are you using?
   - What's the trigger?

4. **Any error details:**
   - Screenshot of the error
   - Or copy the error message

**Quick Self-Check:**
```
[ ] All credentials connected?
[ ] Test data available?
[ ] Trigger actually fired?
[ ] Previous nodes outputting data?
[ ] Expressions using correct paths?
```

The more details you share, the faster I can help you fix it!


instruction: Just give me the code, skip the explanation

output:
I'll be concise! But a quick note: understanding helps you fix issues later.

Here's clean, copy-paste ready code:

```javascript
// Generic n8n Code Node template
const input = $input.first().json;

// Your logic here
const result = {
  processed: true,
  data: input,
  timestamp: new Date().toISOString()
};

return { json: result };
```

**For specific code, tell me:**
- What operation? (filter/transform/API call?)
- Input format?
- Expected output?

I'll give you exactly what you need, minimal explanation. 👍

topic: communication


instruction: Give me a complete n8n workflow JSON for a webhook that sends Slack notifications

output:
Here's a ready-to-import n8n workflow:

```json
{
  "name": "Webhook to Slack",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "slack-notify",
        "responseMode": "responseNode"
      },
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "position": [250, 300]
    },
    {
      "parameters": {
        "channel": "#notifications",
        "text": "=New notification: {{ $json.message }}",
        "otherOptions": {}
      },
      "name": "Slack",
      "type": "n8n-nodes-base.slack",
      "position": [450, 300],
      "credentials": {
        "slackApi": {
          "id": "1",
          "name": "Slack account"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={ "success": true }"
      },
      "name": "Respond",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [650, 300]
    }
  ],
  "connections": {
    "Webhook": {
      "main": [[{"node": "Slack", "type": "main", "index": 0}]]
    },
    "Slack": {
      "main": [[{"node": "Respond", "type": "main", "index": 0}]]
    }
  }
}
```

**To use:**
1. Copy the JSON
2. In n8n: Workflows → Import from File → Paste
3. Connect your Slack credential
4. Activate the workflow
5. POST to: `https://your-n8n.com/webhook/slack-notify`

**Test with curl:**
```bash
curl -X POST https://your-n8n.com/webhook/slack-notify \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello from webhook!"}'
```

complexity: beginner


instruction: Give me a workflow JSON for scheduled database backup to Google Drive

output:
Here's a complete database backup workflow:

```json
{
  "name": "Daily Database Backup",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [{"field": "hours", "hoursInterval": 24}]
        }
      },
      "name": "Daily Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [250, 300]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"
      },
      "name": "Get Tables",
      "type": "n8n-nodes-base.postgres",
      "position": [450, 300],
      "credentials": {"postgres": {"id": "1", "name": "PostgreSQL"}}
    },
    {
      "parameters": {
        "jsCode": "const tables = $input.all().map(i => i.json.table_name);\nconst timestamp = new Date().toISOString().split('T')[0];\nconst backupData = { tables, timestamp, created: new Date().toISOString() };\nreturn { json: { filename: `backup_${timestamp}.json`, content: JSON.stringify(backupData, null, 2) } };"
      },
      "name": "Format Backup",
      "type": "n8n-nodes-base.code",
      "position": [650, 300]
    },
    {
      "parameters": {
        "operation": "upload",
        "folderId": "your-folder-id",
        "fileName": "={{ $json.filename }}",
        "fileContent": "={{ $json.content }}"
      },
      "name": "Upload to Drive",
      "type": "n8n-nodes-base.googleDrive",
      "position": [850, 300],
      "credentials": {"googleDriveOAuth2Api": {"id": "1", "name": "Google Drive"}}
    },
    {
      "parameters": {
        "channel": "#backups",
        "text": "=✅ Database backup completed: {{ $json.filename }}"
      },
      "name": "Notify Slack",
      "type": "n8n-nodes-base.slack",
      "position": [1050, 300],
      "credentials": {"slackApi": {"id": "1", "name": "Slack"}}
    }
  ],
  "connections": {
    "Daily Trigger": {"main": [[{"node": "Get Tables", "type": "main", "index": 0}]]},
    "Get Tables": {"main": [[{"node": "Format Backup", "type": "main", "index": 0}]]},
    "Format Backup": {"main": [[{"node": "Upload to Drive", "type": "main", "index": 0}]]},
    "Upload to Drive": {"main": [[{"node": "Notify Slack", "type": "main", "index": 0}]]}
  }
}
```

**Setup:**
1. Import workflow
2. Connect: PostgreSQL, Google Drive, Slack credentials
3. Update `folderId` with your Drive folder
4. Activate workflow

complexity: intermediate


instruction: Create a workflow JSON for lead capture form to CRM

output:
Here's a complete lead capture workflow:

```json
{
  "name": "Lead Capture to CRM",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "lead-capture",
        "responseMode": "responseNode",
        "options": {"rawBody": false}
      },
      "name": "Lead Form Webhook",
      "type": "n8n-nodes-base.webhook",
      "position": [200, 300]
    },
    {
      "parameters": {
        "jsCode": "const lead = $input.first().json;\n\n// Validate required fields\nconst required = ['name', 'email', 'phone'];\nconst missing = required.filter(f => !lead[f]);\n\nif (missing.length > 0) {\n  throw new Error(`Missing fields: ${missing.join(', ')}`);\n}\n\n// Normalize data\nreturn {\n  json: {\n    name: lead.name.trim(),\n    email: lead.email.toLowerCase().trim(),\n    phone: lead.phone.replace(/\\D/g, ''),\n    source: lead.source || 'website',\n    created_at: new Date().toISOString()\n  }\n};"
      },
      "name": "Validate & Normalize",
      "type": "n8n-nodes-base.code",
      "position": [400, 300]
    },
    {
      "parameters": {
        "resource": "contact",
        "operation": "create",
        "email": "={{ $json.email }}",
        "additionalFields": {
          "firstName": "={{ $json.name.split(' ')[0] }}",
          "lastName": "={{ $json.name.split(' ').slice(1).join(' ') }}",
          "phone": "={{ $json.phone }}"
        }
      },
      "name": "Create HubSpot Contact",
      "type": "n8n-nodes-base.hubspot",
      "position": [600, 300],
      "credentials": {"hubspotApi": {"id": "1", "name": "HubSpot"}}
    },
    {
      "parameters": {
        "fromEmail": "sales@company.com",
        "toEmail": "={{ $json.email }}",
        "subject": "Thanks for reaching out!",
        "text": "Hi {{ $json.name }},\n\nThanks for your interest! We'll be in touch within 24 hours.\n\nBest,\nThe Team"
      },
      "name": "Send Welcome Email",
      "type": "n8n-nodes-base.emailSend",
      "position": [800, 300],
      "credentials": {"smtp": {"id": "1", "name": "SMTP"}}
    },
    {
      "parameters": {
        "channel": "#leads",
        "text": "=🎯 New Lead!\n*Name:* {{ $json.name }}\n*Email:* {{ $json.email }}\n*Source:* {{ $json.source }}"
      },
      "name": "Notify Sales Team",
      "type": "n8n-nodes-base.slack",
      "position": [1000, 300],
      "credentials": {"slackApi": {"id": "1", "name": "Slack"}}
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={ \"success\": true, \"message\": \"Thanks! We'll be in touch.\" }"
      },
      "name": "Success Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [1200, 300]
    }
  ],
  "connections": {
    "Lead Form Webhook": {"main": [[{"node": "Validate & Normalize", "type": "main", "index": 0}]]},
    "Validate & Normalize": {"main": [[{"node": "Create HubSpot Contact", "type": "main", "index": 0}]]},
    "Create HubSpot Contact": {"main": [[{"node": "Send Welcome Email", "type": "main", "index": 0}]]},
    "Send Welcome Email": {"main": [[{"node": "Notify Sales Team", "type": "main", "index": 0}]]},
    "Notify Sales Team": {"main": [[{"node": "Success Response", "type": "main", "index": 0}]]}
  }
}
```

**Features:**
- Input validation
- Data normalization
- CRM integration
- Welcome email
- Team notification
- Webhook response

**Test:**
```bash
curl -X POST https://your-n8n.com/webhook/lead-capture \
  -H "Content-Type: application/json" \
  -d '{"name":"John Doe","email":"john@example.com","phone":"555-1234"}'
```