Analyze email performance & optimize campaigns with GPT-4, SendGrid, and Airtable
Analyze email performance and optimize campaigns with AI using SendGrid and Airtable
This n8n template creates an automated feedback loop that pulls email metrics from SendGrid weekly, tracks performance in Airtable, analyzes trends across the last 4 weeks, and generates specific recommendations for your next campaign. The system learns what works and provides data-driven insights directly to your email creation process.
Who's it for
Email marketers and growth teams who want to continuously improve campaign performance without manual analysis. Perfect for businesses running regular email campaigns who need actionable insights based on real data rather than guesswork.
Good to know
- After 4-6 weeks, expect 15-30% improvement in primary metrics
- Requires at least 2 weeks of historical data to generate meaningful analysis
- System improves over time as it learns from your audience
- Implementation time: ~1 hour total
How it works
- Schedule trigger runs weekly (typically Monday mornings)
- Pulls previous week's email statistics from SendGrid (delivered, opens, clicks, rates)
- Updates the previous week's record in Airtable with actual performance data
- GPT-4 analyzes trends across the last 4 weeks, identifying patterns and opportunities
- Creates a new Airtable record for the upcoming week with specific recommendations: what to test, how to change it, expected outcome, and confidence level
- Your email creation workflow pulls these recommendations when generating new campaigns
- After sending, the actual email content is saved back to Airtable to close the loop
How to set up
- Create Airtable base: Make a table called "Email Campaign Performance" with fields for week_ending, delivered, unique_opens, unique_clicks, open_rate, ctr, decision, test_variable, test_hypothesis, confidence_level, test_directive, implementation_instruction, subject_line_used, email_body, icp, use_case, baseline_performance, success_metric, target_improvement
- Configure SendGrid: Add API key to the "SendGrid Data Pull" node and test connection
- Set up Airtable credentials: Add Personal Access Token and select your base/table in all Airtable nodes
- Add OpenAI credentials: Configure GPT-4 API key in the "Previous Week Analysis" node
- Test with sample data: Manually add 2-3 weeks of data to Airtable or run if you have historical data
- Schedule weekly runs: Set workflow to trigger every Monday at 9 AM (or after your weekly campaign sends)
- Integrate with email creation: Add an Airtable search node to your email workflow to retrieve current recommendations, and an update node to save what was sent
Requirements
- SendGrid account with API access (or similar ESP with statistics API)
- Airtable account with Personal Access Token
- OpenAI API access (GPT-4)
Customizing this workflow
- Use different email platform: Replace SendGrid node with Mailchimp, Brevo, or any ESP that provides statistics APIโadjust field mappings accordingly
- Add more metrics: Extend Airtable fields to track bounce rate, unsubscribe rate, spam complaints, or revenue attribution
- Change analysis frequency: Adjust schedule trigger for bi-weekly or monthly analysis instead of weekly
- Swap AI models: Replace GPT-4 with Claude or Gemini in the analysis node
- Multi-campaign tracking: Duplicate the workflow for different campaign types (newsletters, promotions, onboarding) with separate Airtable tables
Analyze Email Performance & Optimize Campaigns with GPT-4, SendGrid, and Airtable
This n8n workflow automates the analysis of email campaign performance, leveraging the power of GPT-4 for insights and Airtable for data management. It's designed to help marketers and businesses quickly understand what's working in their email campaigns and identify areas for improvement.
What it does
This workflow streamlines the process of analyzing email performance data through the following steps:
- Manual Trigger: The workflow is initiated manually, allowing you to run it on demand. (A Schedule Trigger is also available but disconnected, suggesting it could be configured for automated, periodic runs).
- Fetch Email Data from Airtable: It connects to your Airtable base to retrieve email campaign records.
- Prepare Data for Analysis: A Code node processes the Airtable data, likely extracting relevant fields such as subject lines, body content, open rates, click-through rates, and conversion rates.
- Analyze with OpenAI (GPT-4): The prepared email data is sent to OpenAI's GPT-4 model. GPT-4 analyzes the content and performance metrics, providing insights and suggestions for optimization.
- Merge Data: The original Airtable data is merged with the analysis results from OpenAI.
- Update Airtable: The workflow updates the Airtable records with the new insights and recommendations generated by GPT-4, enriching your campaign data.
Prerequisites/Requirements
To use this workflow, you will need:
- n8n Instance: A running instance of n8n.
- Airtable Account: An Airtable account with a base containing your email campaign data (e.g., columns for subject, body, open rate, click rate, conversion rate).
- OpenAI API Key: An OpenAI API key with access to GPT-4 or a similar large language model.
- SendGrid Account: (Implied by directory name, but not explicitly in JSON) While not directly used in the provided JSON, the directory name suggests an integration with SendGrid. If you intend to use SendGrid for sending emails based on the analysis, you would need a SendGrid account and credentials.
Setup/Usage
- Import the Workflow:
- Download the provided JSON file.
- In your n8n instance, click "Workflows" in the left sidebar.
- Click "New Workflow" and then "Import from JSON".
- Paste the JSON content or upload the file.
- Configure Credentials:
- Airtable: Click on the "Airtable" node, then click "Create New Credential" and provide your Airtable API Key and Base ID.
- OpenAI: Click on the "OpenAI" node, then click "Create New Credential" and enter your OpenAI API Key.
- Customize Nodes:
- Airtable (Read): Configure the "Airtable" node to specify the Base ID and Table Name where your email campaign data is stored.
- Code: Review and adjust the JavaScript code in the "Code" node to ensure it correctly extracts and formats the specific fields from your Airtable data that you want GPT-4 to analyze.
- OpenAI: Configure the "OpenAI" node with the prompt you want to use for GPT-4 to analyze your email data. Ensure it references the data prepared by the "Code" node.
- Airtable (Update): Configure this node to specify the Base ID and Table Name, and map the fields to update with the insights from OpenAI. You'll need to specify how to match records (e.g., by record ID).
- Activate the Workflow: Once all credentials and configurations are set, activate the workflow by toggling the "Active" switch in the top right corner.
- Execute the Workflow: Click "Execute Workflow" to run it manually and see the results. If you wish to automate it, configure the "Schedule Trigger" node to your desired interval and connect it to the workflow.
Related Templates
Auto-create TikTok videos with VEED.io AI avatars, ElevenLabs & GPT-4
๐ฅ Viral TikTok Video Machine: Auto-Create Videos with Your AI Avatar --- ๐ฏ Who is this for? This workflow is for content creators, marketers, and agencies who want to use Veed.ioโs AI avatar technology to produce short, engaging TikTok videos automatically. Itโs ideal for creators who want to appear on camera without recording themselves, and for teams managing multiple brands who need to generate videos at scale. --- โ๏ธ What problem this workflow solves Manually creating videos for TikTok can take hours โ finding trends, writing scripts, recording, and editing. By combining Veed.io, ElevenLabs, and GPT-4, this workflow transforms a simple Telegram input into a ready-to-post TikTok video featuring your AI avatar powered by Veed.io โ speaking naturally with your cloned voice. --- ๐ What this workflow does This automation links Veed.ioโs video-generation API with multiple AI tools: Analyzes TikTok trends via Perplexity AI Writes a 10-second viral script using GPT-4 Generates your voiceover via ElevenLabs Uses Veed.io (Fabric 1.0 via FAL.ai) to animate your avatar and sync the lips to the voice Creates an engaging caption + hashtags for TikTok virality Publishes the video automatically via Blotato TikTok API Logs all results to Google Sheets for tracking --- ๐งฉ Setup Telegram Bot Create your bot via @BotFather Configure it as the trigger for sending your photo and theme Connect Veed.io Create an account on Veed.io Get your FAL.ai API key (Veed Fabric 1.0 model) Use HTTPS image/audio URLs compatible with Veed Fabric Other APIs Add Perplexity, ElevenLabs, and Blotato TikTok keys Connect your Google Sheet for logging results --- ๐ ๏ธ How to customize this workflow Change your Avatar: Upload a new image through Telegram, and Veed.io will generate a new talking version automatically. Modify the Script Style: Adjust the GPT prompt for tone (educational, funny, storytelling). Adjust Voice Tone: Tweak ElevenLabs stability and similarity settings. Expand Platforms: Add Instagram, YouTube Shorts, or X (Twitter) posting nodes. Track Performance: Customize your Google Sheet to measure your most successful Veed.io-based videos. --- ๐ง Expected Outcome In just a few seconds after sending your photo and theme, this workflow โ powered by Veed.io โ creates a fully automated TikTok video featuring your AI avatar with natural lip-sync and voice. The result is a continuous stream of viral short videos, made without cameras, editing, or effort. --- โ Import the JSON file in n8n, add your API keys (including Veed.io via FAL.ai), and start generating viral TikTok videos starring your AI avatar today! ๐ฅ Watch This Tutorial --- ๐ Documentation: Notion Guide Need help customizing? Contact me for consulting and support : Linkedin / Youtube
Generate song lyrics and music from text prompts using OpenAI and Fal.ai Minimax
Spark your creativity instantly in any chatโturn a simple prompt like "heartbreak ballad" into original, full-length lyrics and a professional AI-generated music track, all without leaving your conversation. ๐ What This Template Does This chat-triggered workflow harnesses AI to generate detailed, genre-matched song lyrics (at least 600 characters) from user messages, then queues them for music synthesis via Fal.ai's minimax-music model. It polls asynchronously until the track is ready, delivering lyrics and audio URL back in chat. Crafts original, structured lyrics with verses, choruses, and bridges using OpenAI Submits to Fal.ai for melody, instrumentation, and vocals aligned to the style Handles long-running generations with smart looping and status checks Returns complete song package (lyrics + audio link) for seamless sharing ๐ง Prerequisites n8n account (self-hosted or cloud with chat integration enabled) OpenAI account with API access for GPT models Fal.ai account for AI music generation ๐ Required Credentials OpenAI API Setup Go to platform.openai.com โ API keys (sidebar) Click "Create new secret key" โ Name it (e.g., "n8n Songwriter") Copy the key and add to n8n as "OpenAI API" credential type Test by sending a simple chat completion request Fal.ai HTTP Header Auth Setup Sign up at fal.ai โ Dashboard โ API Keys Generate a new API key โ Copy it In n8n, create "HTTP Header Auth" credential: Name="Fal.ai", Header Name="Authorization", Header Value="Key [Your API Key]" Test with a simple GET to their queue endpoint (e.g., /status) โ๏ธ Configuration Steps Import the workflow JSON into your n8n instance Assign OpenAI API credentials to the "OpenAI Chat Model" node Assign Fal.ai HTTP Header Auth to the "Generate Music Track", "Check Generation Status", and "Fetch Final Result" nodes Activate the workflowโchat trigger will appear in your n8n chat interface Test by messaging: "Create an upbeat pop song about road trips" ๐ฏ Use Cases Content Creators: YouTubers generating custom jingles for videos on the fly, streamlining production from idea to audio export Educators: Music teachers using chat prompts to create era-specific folk tunes for classroom discussions, fostering interactive learning Gift Personalization: Friends crafting anniversary R&B tracks from shared memories via quick chats, delivering emotional audio surprises Artist Brainstorming: Songwriters prototyping hip-hop beats in real-time during sessions, accelerating collaboration and iteration โ ๏ธ Troubleshooting Invalid JSON from AI Agent: Ensure the system prompt stresses valid JSON; test the agent standalone with a sample query Music Generation Fails (401/403): Verify Fal.ai API key has minimax-music access; check usage quotas in dashboard Status Polling Loops Indefinitely: Bump wait time to 45-60s for complex tracks; inspect fal.ai queue logs for bottlenecks Lyrics Under 600 Characters: Tweak agent prompt to enforce fuller structures like [V1][C][V2][B][C]; verify output length in executions
Automate invoice processing with OCR, GPT-4 & Salesforce opportunity creation
PDF Invoice Extractor (AI) End-to-end pipeline: Watch Drive โ Download PDF โ OCR text โ AI normalize to JSON โ Upsert Buyer (Account) โ Create Opportunity โ Map Products โ Create OLI via Composite API โ Archive to OneDrive. --- Node by node (what it does & key setup) 1) Google Drive Trigger Purpose: Fire when a new file appears in a specific Google Drive folder. Key settings: Event: fileCreated Folder ID: google drive folder id Polling: everyMinute Creds: googleDriveOAuth2Api Output: Metadata { id, name, ... } for the new file. --- 2) Download File From Google Purpose: Get the file binary for processing and archiving. Key settings: Operation: download File ID: ={{ $json.id }} Creds: googleDriveOAuth2Api Output: Binary (default key: data) and original metadata. --- 3) Extract from File Purpose: Extract text from PDF (OCR as needed) for AI parsing. Key settings: Operation: pdf OCR: enable for scanned PDFs (in options) Output: JSON with OCR text at {{ $json.text }}. --- 4) Message a model (AI JSON Extractor) Purpose: Convert OCR text into strict normalized JSON array (invoice schema). Key settings: Node: @n8n/n8n-nodes-langchain.openAi Model: gpt-4.1 (or gpt-4.1-mini) Message role: system (the strict prompt; references {{ $json.text }}) jsonOutput: true Creds: openAiApi Output (per item): $.message.content โ the parsed JSON (ensure itโs an array). --- 5) Create or update an account (Salesforce) Purpose: Upsert Buyer as Account using an external ID. Key settings: Resource: account Operation: upsert External Id Field: taxid_c External Id Value: ={{ $json.message.content.buyer.tax_id }} Name: ={{ $json.message.content.buyer.name }} Creds: salesforceOAuth2Api Output: Account record (captures Id) for downstream Opportunity. --- 6) Create an opportunity (Salesforce) Purpose: Create Opportunity linked to the Buyer (Account). Key settings: Resource: opportunity Name: ={{ $('Message a model').item.json.message.content.invoice.code }} Close Date: ={{ $('Message a model').item.json.message.content.invoice.issue_date }} Stage: Closed Won Amount: ={{ $('Message a model').item.json.message.content.summary.grand_total }} AccountId: ={{ $json.id }} (from Upsert Account output) Creds: salesforceOAuth2Api Output: Opportunity Id for OLI creation. --- 7) Build SOQL (Code / JS) Purpose: Collect unique product codes from AI JSON and build a SOQL query for PricebookEntry by Pricebook2Id. Key settings: pricebook2Id (hardcoded in script): e.g., 01sxxxxxxxxxxxxxxx Source lines: $('Message a model').first().json.message.content.products Output: { soql, codes } --- 8) Query PricebookEntries (Salesforce) Purpose: Fetch PricebookEntry.Id for each Product2.ProductCode. Key settings: Resource: search Query: ={{ $json.soql }} Creds: salesforceOAuth2Api Output: Items with Id, Product2.ProductCode (used for mapping). --- 9) Code in JavaScript (Build OLI payloads) Purpose: Join lines with PBE results and Opportunity Id โ build OpportunityLineItem payloads. Inputs: OpportunityId: ={{ $('Create an opportunity').first().json.id }} Lines: ={{ $('Message a model').first().json.message.content.products }} PBE rows: from previous node items Output: { body: { allOrNone:false, records:[{ OpportunityLineItem... }] } } Notes: Converts discount_total โ per-unit if needed (currently commented for standard pricing). Throws on missing PBE mapping or empty lines. --- 10) Create Opportunity Line Items (HTTP Request) Purpose: Bulk create OLIs via Salesforce Composite API. Key settings: Method: POST URL: https://<your-instance>.my.salesforce.com/services/data/v65.0/composite/sobjects Auth: salesforceOAuth2Api (predefined credential) Body (JSON): ={{ $json.body }} Output: Composite API results (per-record statuses). --- 11) Update File to One Drive Purpose: Archive the original PDF in OneDrive. Key settings: Operation: upload File Name: ={{ $json.name }} Parent Folder ID: onedrive folder id Binary Data: true (from the Download node) Creds: microsoftOneDriveOAuth2Api Output: Uploaded file metadata. --- Data flow (wiring) Google Drive Trigger โ Download File From Google Download File From Google โ Extract from File โ Update File to One Drive Extract from File โ Message a model Message a model โ Create or update an account Create or update an account โ Create an opportunity Create an opportunity โ Build SOQL Build SOQL โ Query PricebookEntries Query PricebookEntries โ Code in JavaScript Code in JavaScript โ Create Opportunity Line Items --- Quick setup checklist ๐ Credentials: Connect Google Drive, OneDrive, Salesforce, OpenAI. ๐ IDs: Drive Folder ID (watch) OneDrive Parent Folder ID (archive) Salesforce Pricebook2Id (in the JS SOQL builder) ๐ง AI Prompt: Use the strict system prompt; jsonOutput = true. ๐งพ Field mappings: Buyer tax id/name โ Account upsert fields Invoice code/date/amount โ Opportunity fields Product name must equal your Product2.ProductCode in SF. โ Test: Drop a sample PDF โ verify: AI returns array JSON only Account/Opportunity created OLI records created PDF archived to OneDrive --- Notes & best practices If PDFs are scans, enable OCR in Extract from File. If AI returns non-JSON, keep โReturn only a JSON arrayโ as the last line of the prompt and keep jsonOutput enabled. Consider adding validation on parsing.warnings to gate Salesforce writes. For discounts/taxes in OLI: Standard OLI fields donโt support per-line discount amounts directly; model them in UnitPrice or custom fields. Replace the Composite API URL with your orgโs domain or use the Salesforce nodeโs Bulk Upsert for simplicity.