Opening Problem Statement
Meet Giorgio, an IT security analyst at a mid-sized financial firm. Every week, Giorgio spends countless hours manually scrutinizing suspicious emails reported by employees. He extracts headers, hunts down IP addresses, and cross-checks reputation services. Mistakes happen, false negatives slip past, and time is wasted on erroneous leads. With phishing and spoofing attempts rising, Giorgio needs a reliable, automated process to analyze email headers for potential spoofing and malicious IPs quickly and accurately.
This is where our n8n workflow shines — providing a powerful automation tailored to dissect email headers and evaluate IP reputations, SPF, DKIM, and DMARC authentication — all in one streamlined sequence.
What This Automation Does
When triggered via webhook with an email header payload, this n8n workflow performs several precise functions:
- Extracts and parses the email header string to divide it into analyzable components.
- Identifies IP addresses from “Received” headers and individually evaluates each using the IP Quality Score API to assess fraud, abuse, and reputation risks.
- Queries IP geolocation and ISP details via the IP-API, adding context to each IP’s origin.
- Assesses email authentication by examining SPF, DKIM, and DMARC results parsed from the email headers.
- Aggregates all data into a cohesive structured JSON response, merging both IP reputation and authentication status.
- Responds via webhook with detailed analysis results, ready for immediate security action or further integration.
This automation can save Giorgio hours per week, eliminate manual errors, and enhance email phishing defenses by providing actionable intelligence in real-time.
Prerequisites ⚙️
- n8n account with access to create workflows and HTTP Request nodes 🔑
- IP Quality Score API key (free tier available for 5000 credits/month) 🔐
- Internet access to use IP Quality Score and IP-API services 🔌
- Webhook endpoint to trigger the workflow with email header data 📧
- Basic familiarity with n8n node configurations ⏱️
Step-by-Step Guide
Step 1: Create a Webhook to Receive Email Headers
In your n8n workflow editor, click + Add Node → Webhook. Name it Receive Headers. Set the HTTP Method to POST and define a unique path, e.g., 90e9e395-1d40-4575-b2a0-fbf52c534167. This node will accept incoming email header data as plain text.
Once set, you should see the webhook URL. You can test it later by sending an email header payload via a tool like Postman. The webhook confirms it received data by invoking the next steps.
Common Mistake: Forgetting to set the HTTP method to POST will block incoming data.
Step 2: Extract the Raw Email Header Text
Add a Set node named Extract Email Header from webhook right after the webhook. Configure it to keep only one string field named header with the expression {{$json.body}} retrieving the raw header text.
This step isolates the header content for parsing. You should see the raw email headers as the node output.
Step 3: Break Down the Header into Structured Data
Insert a Code node called Explode Email Header to parse the header string line-by-line and convert each header entry into key-value pairs. Use this JavaScript snippet:
let returnArray = [];
for (const item of $input.all()) {
const headerStr = item.json.header;
const headerLines = headerStr.split('n');
const headerObj = {};
let currentKey = null;
let currentValue = '';
headerLines.forEach((line) => {
const match = line.match(/^([w-]+):s*(.*)/);
if (match) {
if (currentKey) {
if (!headerObj[currentKey]) headerObj[currentKey] = [];
headerObj[currentKey].push({ [currentKey]: currentValue });
}
currentKey = match[1].toLowerCase();
currentValue = match[2];
} else {
currentValue += ' ' + line.trim();
}
});
if (currentKey) {
if (!headerObj[currentKey]) headerObj[currentKey] = [];
headerObj[currentKey].push({ [currentKey + 'Item']: currentValue });
}
returnArray.push({ "header": headerObj });
}
return returnArray;You should see a structured JSON response where each header field corresponds to an array of string values.
Step 4: Conditional Paths Based on Header Importance
Add two If nodes named Received Headers Present? and Authentication Results Present?. Configure them to check if the respective header arrays have length > 0.
This splits the workflow path: one branch handles received IP extraction, the other handles authentication analysis.
Step 5: Extract IP Addresses from “Received” Headers
On the true branch from Received Headers Present?, add a Code node named Extract IPs from “received” with this JS code:
let ips = [];
for (const item of $input.all()) {
const header = JSON.stringify(item.json.header.received);
const ipRegex = /bd{1,3}.d{1,3}.d{1,3}.d{1,3}b/g;
const ipAddresses = header.match(ipRegex) || [];
ips.push(...ipAddresses);
}
return [ { ips: ips } ];This pulls all IPv4 addresses out of the header’s received entries.
Step 6: Split IPs for Individual Processing
Add an Item Lists node named Split Out IPs to split the IP list into individual items for API querying. Set the field to split out to ips and the destination field ip.
Step 7: Query IP Reputation with IP Quality Score API
Add an HTTP Request node named IP Quality Score. Use the GET method with URL:
=https://ipqualityscore.com/api/json/ip/{{ YOUR_API_KEY }}/{{ $json.ip }}?strictness=1&allow_public_access_points=true&lighter_penalties=trueReplace YOUR_API_KEY with your API key hardcoded as the node currently lacks secret injection.
This retrieves detailed fraud and abuse data for each IP.
Step 8: Query Geolocation Info with IP-API
Add another HTTP Request node named IP-API with method POST to:
=http://ip-api.com/json/{{ $json.ip }}This provides context like ISP and geolocation.
Step 9: Calculate Spam Activity and Reputation Descriptions
Add a Code node named Fraud Score, running once per IP item, with included JavaScript to interpret the fraud score numerically and convert into qualitative descriptors like “Bad” or “Good” reputation, and also flag recent spam activity.
Step 10: Collect Relevant IP Data
Use a Set node called Collect interesting data to assemble key fields from IP Quality Score and IP-API responses along with the fraud score interpretations into a unified object per IP.
Step 11: Merge All IP Analysis Results
Add a Merge node named IP Data Merge and attach an Item Lists node called Join IP Analysis into one JSON object to aggregate all IP data into a single array ipAnalysis.
Step 12: Analyze Email Authentication Fields
On the true branch of Authentication Results Present?, add a Code node named SPF/DKIM/DMARC from “authentication-results” that scans the authentication-results header string and extracts pass/fail/neutral states for SPF, DKIM, and DMARC.
Step 13: Additional SPF, DKIM, and DMARC Extraction
Add Code nodes named SPF from “received-spf”, DKIM from “dkim-signature”, and DMARC from “received-dmarc” that parse their respective header fields and summarize status.
Step 14: Aggregate Authentication Data
Use a Set node called Aggregate Authentication Data to consolidate SPF, DKIM, and DMARC results into one object.
Step 15: Merge Security Data and Final Responses
Merge the IP analysis JSON object with the authentication data using two Merge nodes named Merge Security Data and Join results into one JSON object. Finally, the Respond to Webhook node returns the compiled detailed security analysis with HTTP 200 response.
Customizations ✏️
- Add DKIM Detailed Verification: Extend the DKIM from “dkim-signature” Code node to check for signature validity and alignment, adding a more granular pass/fail status.
- Whitelist Trusted IPs: Add a Code node to cross-reference IP addresses against a known safe list, marking them to bypass further fraud checks for internal email sources.
- Extend IP Quality Parameters: Modify the HTTP Request to IP Quality Score to include parameters like VPN detection or anonymizer flags for deeper threat intelligence.
- Add Logging: Include an n8n Write Binary File or Google Sheets node to log suspicious IPs and authentication fails for audit trails.
- Integrate Slack Alerts: Trigger Slack notifications for any IPs with a “Bad” reputation detected, enhancing real-time monitoring.
Troubleshooting 🔧
- Problem: “IP Quality Score API returns 401 Unauthorized”
Cause: Incorrect or missing API key in the HTTP Request node.
Solution: Verify API key is hardcoded correctly in the IP Quality Score URL. Re-generate key if necessary. - Problem: “Webhook never receives data”
Cause: Webhook path mismatch or HTTP method incorrect.
Solution: Confirm webhook URL and ensure the requester posts via HTTP POST. - Problem: “Rate limiting errors from IP-API”
Cause: Exceeding 45 requests per minute from the same IP.
Solution: Implement throttling in n8n or batch IPs to stay within limits.
Pre-Production Checklist ✅
- Confirm Webhook is live and accessible
- Test with valid email header samples, confirm IP extraction accuracy
- Validate API key and test IP Quality Score API calls
- Check outputs of SPF/DKIM/DMARC code nodes for correct parsing
- Ensure final JSON output matches expected data structure for integration
Deployment Guide
Activate the workflow in n8n by turning the toggle ON. Ensure your webhook endpoint is securely exposed to your data source. Set up monitoring in n8n’s execution UI to watch for errors or slowdowns. Logs can be reviewed for troubleshooting. This workflow is ready for production as is or can be nested within larger automation pipelines for email security workflow orchestration.
Conclusion
By implementing this custom n8n workflow, Giorgio and your security team gain a robust tool to automatically analyze email header data for spoofing risks and IP reputation insights. It streamlines a previously tedious process, saving hours weekly and reducing phishing threats from unknown sources. You now have a replicable, scalable email header analysis automation that can be extended for broader organizational email security needs.
Next steps might include integrating alerting channels like Slack or email, expanding to analyze other header patterns, or correlating reports with SIEM tools for comprehensive threat intelligence.