Automating Email Organization with n8n and OpenAI: A Self-Hosted Solution

Automating Email Organization with n8n and OpenAI: A Self-Hosted Solution

Email overload is a common problem for professionals and businesses. While manual labeling helps organize emails, it's time-consuming and inconsistent. This guide shows how to build an automated email labeling system using n8n, OpenAI, and Gmail.

Why Automate Email Labeling?

  • Time Savings: Eliminate manual categorization of hundreds of emails
  • Consistency: Ensure uniform labeling across all incoming emails
  • Customization: Create rules specific to your workflow
  • Privacy: Self-host the solution to maintain data control

System Architecture

The workflow consists of:

  1. Gmail integration for monitoring new emails
  2. n8n for workflow orchestration
  3. OpenAI for intelligent content analysis
  4. PostgreSQL for data persistence
  5. Docker for containerization

What is n8n?

n8n (pronounced as "node-n") is a fair-code licensed workflow automation platform. Key features include:

  • Visual Workflow Builder: Create automation flows through an intuitive interface
  • Node-Based Architecture: Each action is a node that can be connected to others
  • Self-Hosting: Deploy on your own infrastructure for data control
  • 800+ Integrations: Connect with popular services and APIs
  • Custom Functions: Write JavaScript code for complex logic
  • Real-Time Execution: Monitor and debug workflows as they run
  • Version Control: Track changes and restore previous versions
  • Error Handling: Built-in retry mechanisms and error workflows

Why Choose n8n?

  1. Data Privacy
    • Self-hosted solution keeps sensitive data on your infrastructure
    • No vendor lock-in
    • Complete control over upgrades and maintenance
  2. Cost-Effectiveness
    • One-time setup cost
    • No per-user or per-execution fees
    • Scale without increasing costs
  3. Flexibility
    • Customize every aspect of the workflow
    • Add custom nodes and functions
    • Integrate with any API or service

Prerequisites

  • A server (Linux recommended)
  • Docker and Docker Compose
  • Gmail account
  • OpenAI API key

Setting Up the Infrastructure

1. Create the Docker Compose File

Create docker-compose.yml:

version: '3.8'

services:
  n8n:
    image: n8nio/n8n
    ports:
      - "5678:5678"
    environment:
      - N8N_HOST=${N8N_HOST}
      - N8N_PORT=5678
      - N8N_PROTOCOL=http
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=postgres
      - DB_POSTGRESDB_DATABASE=n8n
      - DB_POSTGRESDB_USER=n8n
      - DB_POSTGRESDB_PASSWORD=${DB_PASSWORD}
    depends_on:
      - postgres
    volumes:
      - n8n_data:/home/node/.n8n

  postgres:
    image: postgres:13
    environment:
      - POSTGRES_DB=n8n
      - POSTGRES_USER=n8n
      - POSTGRES_PASSWORD=${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  n8n_data:
  postgres_data:

2. Create Environment File

Create .env:

N8N_HOST=your-domain.com
DB_PASSWORD=your-secure-password

3. Start the Services

docker-compose up -d

Configuring the Workflow

  1. Access n8n at http://your-domain:5678
  2. Create credentials:
    • Gmail (OAuth2)
    • OpenAI API key
  3. Build the workflow:
    • Gmail Trigger node: Monitor for new emails
    • Gmail node: Get email details
    • Code node: Extract email content
    • OpenAI node: Analyze content and suggest labels
    • Gmail node: Apply labels

The Workflow in Detail

Gmail Trigger Setup

  • Configure polling interval
  • Set filters for specific email pattern

Creating Google Cloud Project

  1. Go to Google Cloud Console
  2. Create a new project or select existing one
  3. Enable Gmail API:
    • Navigate to "APIs & Services" > "Library"
    • Search for "Gmail API"
    • Click "Enable"
  1. Go to "APIs & Services" > "OAuth consent screen"
  2. Select "External" user type
  3. Fill required information:
    • App name
    • User support email
    • Developer contact email
  4. Add scopes:
    • https://www.googleapis.com/auth/gmail.labels
    • https://www.googleapis.com/auth/gmail.modify
    • https://www.googleapis.com/auth/gmail.compose

Create OAuth Credentials

  1. Go to "APIs & Services" > "Credentials"
  2. Click "Create Credentials" > "OAuth client ID"
  3. Select "Web application"
  4. Add authorized redirect URIs:

Content Analysis with OpenAI

// Example prompt for OpenAI
const prompt = `Analyze the following email and suggest appropriate labels:
Subject: ${input.subject}
Body: ${input.body}

Suggest labels from the following categories:
- Priority (High/Medium/Low)
- Department (Sales/Marketing/Support/Technical)
- Action (Follow-up/Review/Archive)`;

Label Application

  • Create labels programmatically if they don't exist
  • Apply multiple labels based on OpenAI's analysis
  • Handle edge cases and errors

Security Considerations

  1. Data Privacy
    • Self-hosted infrastructure keeps data in your control
    • Restrict network access to n8n interface
    • Use HTTPS for production deployments
  2. API Security
    • Rotate API keys regularly
    • Monitor usage and set rate limits
    • Implement access controls

Maintenance and Monitoring

  1. Regular tasks:
    • Check n8n logs for errors
    • Monitor PostgreSQL database size
    • Update Docker images
    • Verify Gmail API quotas
  2. Backup strategy:
    • PostgreSQL data backup
    • n8n workflow export
    • Environment configuration backup

Extending the Solution

Consider these enhancements:

  • Add Slack notifications for important emails
  • Create custom labeling rules
  • Implement sentiment analysis
  • Generate email summaries
  • Auto-reply capabilities

Conclusion

This automated email labeling system demonstrates how modern tools can solve common productivity challenges. By combining n8n's workflow capabilities with OpenAI's intelligence, you can create a powerful, customizable solution for email management.

Remember to adjust the configuration based on your specific needs and email volume. The system can be enhanced further with additional integrations and custom logic as your requirements evolve.