n8n Automation

n8n Email Automation: Complete Workflow Implementation Guide

Petru Constantin
••12 min read
#n8n#email automation#workflow automation#SMTP#IMAP

Email workflows in n8n come down to a few nodes: Email Trigger (IMAP) to receive, Send Email (SMTP) to send, Code nodes to render templates and check attachments, and the Loop Over Items and Wait nodes to pace sending. This guide builds each piece, including attachment handling, bounce processing and a fallback to other channels.

Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the n8n 2.47 (stable release line, November 2026), Email Trigger (IMAP), Send Email and Code nodes documentation.

Email Node Configuration

SMTP Integration Setup

Configure reliable SMTP sending with proper authentication:

In n8n, the SMTP connection is a credential, not node JSON. Create an SMTP credential with User, Password (often an app password or the provider's SMTP key), Host (for example smtp.<provider>.com) and Port. Match the port to the encryption: 465 with SSL/TLS on, 587 with SSL/TLS off (the server upgrades with STARTTLS), and avoid 25 without encryption. Leave Client Host Name empty unless your provider asks for it. The Send Email node then selects this credential.

IMAP Email Trigger

Monitor inboxes for incoming emails:

Configure the Email Trigger (IMAP) node in its panel: select the IMAP credential, set Mailbox Name (for example INBOX), choose under Action whether received emails are marked as read, turn on Download Attachments if later nodes need the files, and pick a Format (Resolved returns the email with attachments saved as binary data; Simple should not be used if you need inline attachments). Under options, Custom Email Rules sets which emails the node fetches and Force Reconnect Every Minutes forces a fresh connection at an interval, which helps with servers that drop idle IMAP sessions.

Template Engine Implementation

Dynamic Email Templates

Create reusable templates with variable substitution:

// n8n Code node (JavaScript), mode: Run Once for All Items
// Renders {{name}} placeholders and {{#each list}}...{{/each}} blocks.
// Every inserted value is HTML-escaped, so customer data cannot inject markup.
const templates = {
  welcome: {
    subject: 'Welcome to {{company}}, {{firstName}}!',
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <h1 style="color: #2563eb;">Welcome, {{firstName}}!</h1>
        <p>Thank you for joining {{company}}.</p>
        <h3>Getting started</h3>
        <ul>{{#each onboardingSteps}}<li>{{this}}</li>{{/each}}</ul>
        <a href="{{dashboardUrl}}" style="display: inline-block; background: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px;">Go to Dashboard</a>
        <p style="margin-top: 30px; color: #6b7280; font-size: 14px;">Need help? Visit our <a href="{{supportUrl}}">support center</a>.</p>
      </div>`
  },
  orderConfirmation: {
    subject: 'Order #{{orderId}} Confirmed',
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <h1>Order confirmed</h1>
        <p>Hi {{firstName}}, your order has been confirmed.</p>
        <table style="width: 100%; border-collapse: collapse;">
          <tr><th style="text-align: left;">Item</th><th style="text-align: right;">Qty</th><th style="text-align: right;">Price</th></tr>
          {{#each items}}<tr><td>{{name}}</td><td style="text-align: right;">{{quantity}}</td><td style="text-align: right;">{{price}}</td></tr>{{/each}}
          <tr><td colspan="2" style="text-align: right; font-weight: bold;">Total:</td><td style="text-align: right; font-weight: bold;">{{total}}</td></tr>
        </table>
      </div>`
  }
};
 
const escapeHtml = (value) => String(value ?? '')
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;')
  .replace(/'/g, '&#39;');
 
function fillVariables(text, vars, escape) {
  return text.replace(/\{\{(\w+)\}\}/g, (match, key) => {
    if (key === 'this' && 'this' in vars) return escape(vars.this);
    return key in vars ? escape(vars[key]) : '';
  });
}
 
function render(templateName, data) {
  const template = templates[templateName];
  if (!template) throw new Error(`Template '${templateName}' not found`);
 
  // Expand {{#each list}} blocks first
  let html = template.html.replace(/\{\{#each (\w+)\}\}([\s\S]*?)\{\{\/each\}\}/g, (match, key, block) => {
    const list = Array.isArray(data[key]) ? data[key] : [];
    return list
      .map(entry => fillVariables(block, typeof entry === 'object' ? entry : { this: entry }, escapeHtml))
      .join('');
  });
 
  html = fillVariables(html, data, escapeHtml);
  // The subject is plain text: no HTML escaping, but strip line breaks
  const subject = fillVariables(template.subject, data, v => String(v ?? '').replace(/[\r\n]+/g, ' '));
 
  return { subject, html };
}
 
return $input.all().map(item => {
  const { to, templateName, variables, replyTo } = item.json;
  const rendered = render(templateName, variables || {});
  return {
    json: {
      to,
      subject: rendered.subject,
      html: rendered.html,
      replyTo: replyTo || 'noreply@example.com'
    }
  };
});

Attachment Handling

Processing Email Attachments

Handle incoming attachments securely:

// n8n Code node (JavaScript), mode: Run Once for All Items
// Input: emails from the Email Trigger (IMAP) node with Download Attachments on.
// Attachments arrive as binary properties on each item (item.binary).
const allowedMimeTypes = [
  'application/pdf',
  'image/jpeg',
  'image/png',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'text/csv'
];
const maxSizeBytes = 10 * 1024 * 1024; // 10 MB
 
const items = $input.all();
const output = [];
 
for (let i = 0; i < items.length; i++) {
  const item = items[i];
  const keptBinary = {};
  const accepted = [];
  const rejected = [];
 
  for (const [property, file] of Object.entries(item.binary || {})) {
    if (!allowedMimeTypes.includes(file.mimeType)) {
      rejected.push({ fileName: file.fileName, reason: `type ${file.mimeType}` });
      continue;
    }
 
    // Read the real size from the buffer
    const buffer = await this.helpers.getBinaryDataBuffer(i, property);
    if (buffer.length > maxSizeBytes) {
      rejected.push({ fileName: file.fileName, reason: `size ${buffer.length} bytes` });
      continue;
    }
 
    const safeName = String(file.fileName || property)
      .replace(/[^a-zA-Z0-9.-]/g, '_')
      .substring(0, 255);
 
    keptBinary[property] = { ...file, fileName: safeName };
    accepted.push({ property, fileName: safeName, mimeType: file.mimeType, sizeBytes: buffer.length });
  }
 
  output.push({
    json: { ...item.json, acceptedAttachments: accepted, rejectedAttachments: rejected },
    binary: keptBinary,
    pairedItem: { item: i }
  });
}
 
return output;

Creating Email Attachments

Generate and attach files dynamically:

// n8n Code node (JavaScript), mode: Run Once for Each Item
// Builds an invoice as HTML and returns it base64-encoded. Next node:
// Convert to File, operation "Move Base64 String to File", with File Name
// {{ $json.attachment.fileName }} and MIME Type text/html. Then reference
// that binary property under Attachments in the Send Email node.
// To send a PDF instead, render this HTML with a PDF service first.
const order = $input.item.json;
 
const escapeHtml = (value) => String(value ?? '')
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;');
 
const rows = (order.items || [])
  .map(item => `<tr><td>${escapeHtml(item.name)}</td><td>${escapeHtml(item.qty)}</td><td>${escapeHtml(item.price)}</td></tr>`)
  .join('');
 
const invoiceHtml = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: Arial, sans-serif; margin: 40px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 10px; text-align: left; border-bottom: 1px solid #e5e7eb; }
    .total { font-weight: bold; font-size: 18px; }
  </style>
</head>
<body>
  <h1>Invoice #${escapeHtml(order.invoiceNumber)}</h1>
  <p>Date: ${DateTime.now().toISODate()}</p>
  <table>
    <tr><th>Item</th><th>Qty</th><th>Price</th></tr>
    ${rows}
  </table>
  <p class="total">Total: ${escapeHtml(order.total)} ${escapeHtml(order.currency || '')}</p>
</body>
</html>`;
 
return {
  json: {
    ...order,
    attachment: {
      fileName: `invoice-${String(order.invoiceNumber).replace(/[^a-zA-Z0-9-]/g, '_')}.html`,
      base64: Buffer.from(invoiceHtml, 'utf-8').toString('base64')
    }
  }
};

Multi-Channel Orchestration

Email with SMS Fallback

Implement reliable delivery with fallbacks:

// Workflow: Multi-Channel Notification
// Node 1: Determine Channel Priority
 
const notification = $input.first().json;
const userPreferences = notification.userPreferences;
 
const channels = [];
 
// Build channel priority based on urgency and preferences
if (notification.urgency === 'critical') {
  // Critical: SMS first, then email
  if (userPreferences.smsEnabled) channels.push('sms');
  channels.push('email');
  if (userPreferences.pushEnabled) channels.push('push');
} else if (notification.urgency === 'high') {
  // High: Email and push simultaneously
  channels.push('email');
  if (userPreferences.pushEnabled) channels.push('push');
} else {
  // Normal: Email only
  channels.push('email');
}
 
return [{
  json: {
    ...notification,
    channelPriority: channels,
    currentChannel: 0,
    deliveryAttempts: []
  }
}];
// Node 2: Send via Current Channel (Switch Node routes to appropriate sender)
 
// After sending, track delivery status
const result = $input.first().json;
const deliveryAttempt = {
  channel: result.channel,
  timestamp: new Date().toISOString(),
  success: result.success,
  messageId: result.messageId,
  error: result.error || null
};
 
result.deliveryAttempts.push(deliveryAttempt);
 
// Check if we need fallback
if (!result.success && result.currentChannel < result.channelPriority.length - 1) {
  // Move to next channel
  result.currentChannel++;
  result.needsRetry = true;
} else {
  result.needsRetry = false;
  result.finalStatus = result.success ? 'delivered' : 'failed';
}
 
return [{ json: result }];

Email Queue Management

Rate-Limited Email Queue

Pace the sending with the Loop Over Items node and a Wait node. n8n's rate-limit guide puts it this way: use the Loop Over Items node to batch the input items, and the Wait node to introduce a pause between each request. Set the batch size and the pause from your provider's sending limits, then route the loop output to the Send Email node and back:

  1. Loop Over Items, Batch Size 10 (example value).
  2. Send Email on the loop output, with To Email {{ $json.to }}, Subject {{ $json.subject }}, Email Format HTML.
  3. Wait for the pause you derived from your provider's limit (for example 6 seconds for 10 emails gives about 100 per minute).
  4. Connect the Wait node back to Loop Over Items; the done output continues once every batch is sent.

If your provider has its own API with batch sending, the HTTP Request node's Batching option ("control how many requests the node sends before pausing") does the same pacing in one node.

Bounce and Complaint Handling

Process email bounces and maintain list hygiene:

// n8n Code node (JavaScript), mode: Run Once for Each Item
// Input: a bounce/complaint webhook from your email provider. The field names
// (eventType, bounceType, email) are an example: map them to your provider's payload.
const event = $input.item.json.body ?? $input.item.json;
 
let action = 'none';
let severity = 'info';
 
switch (event.eventType) {
  case 'bounce':
    if (event.bounceType === 'Permanent') {
      action = 'unsubscribe';            // hard bounce: stop sending
      severity = 'high';
    } else {
      action = 'increment_soft_bounce';  // soft bounce: count and retry later
      severity = 'medium';
    }
    break;
  case 'complaint':
    action = 'unsubscribe';              // spam complaint: remove at once
    severity = 'critical';
    break;
  case 'unsubscribe':
    action = 'unsubscribe';
    break;
}
 
return {
  json: {
    email: event.email,
    eventType: event.eventType,
    action,
    severity,
    timestamp: new Date().toISOString(),
    rawEvent: event
  }
};

Email Analytics and Tracking

Open and Click Tracking

Implement tracking pixel and link rewriting:

// n8n Code node (JavaScript), mode: Run Once for Each Item
// trackingDomain is your own tracking endpoint (placeholder below).
const email = $input.item.json;
const trackingDomain = 'https://track.example.com';
const emailId = email.emailId || `email_${$execution.id}_${$itemIndex}`;
 
// 1x1 pixel for open tracking (many mail clients block or proxy images)
const trackingPixel = `<img src="${trackingDomain}/open/${encodeURIComponent(emailId)}" width="1" height="1" style="display:none;" alt="" />`;
 
// Rewrite links for click tracking, except mailto: and tel:
const linkRegex = /<a\s+([^>]*href=["'])([^"']+)(["'][^>]*)>/gi;
let trackedHtml = String(email.html || '').replace(linkRegex, (match, before, url, after) => {
  if (url.startsWith('mailto:') || url.startsWith('tel:')) return match;
  const trackedUrl = `${trackingDomain}/click/${encodeURIComponent(emailId)}?url=${encodeURIComponent(url)}`;
  return `<a ${before}${trackedUrl}${after}>`;
});
 
// Pixel before </body>, or at the end if the HTML has no body tag
trackedHtml = trackedHtml.includes('</body>')
  ? trackedHtml.replace('</body>', `${trackingPixel}</body>`)
  : trackedHtml + trackingPixel;
 
return {
  json: {
    ...email,
    emailId,
    html: trackedHtml,
    tracking: { openPixelUrl: `${trackingDomain}/open/${encodeURIComponent(emailId)}`, enabled: true }
  }
};

Error Handling and Retry Logic

Resilient Email Sending with Retries

Retries belong in the Send Email node's settings, not in a Code node. Turn on Retry On Fail; n8n's rate-limit guide notes that "Wait Between Tries is limited to 5000 ms (5 seconds), and Max Tries is limited to five." Then set On Error to Continue (using error output) so an email that still fails goes to a separate branch: log it, add it to a retry table that a Schedule Trigger workflow picks up later, or hand it to the SMS fallback from the multi-channel section. Keep the retry for temporary failures; an address the server rejects permanently belongs in the suppression list instead.

Production Workflow Example

Complete Transactional Email Workflow

The transactional email workflow, node by node:

  1. Webhook (POST, path send-email, Authentication: Header Auth with a header credential), Respond: when the last node finishes or with a Respond to Webhook node.
  2. Code "Validate Request" (Run Once for Each Item): checks that to, templateName and variables exist and that to is a valid address; throws an error otherwise.
  3. Code "Render Template": the renderer from the template section above.
  4. Postgres "Check Suppression List", Execute Query SELECT 1 FROM email_suppressions WHERE email = $1 LIMIT 1 with {{ $json.to }} in Query Parameters, and Always Output Data on so an address that is not suppressed still produces an item.
  5. If: continue only when the suppression query returned no row.
  6. Send Email: From Email from a Set node with your sender address, To Email {{ $json.to }}, Subject {{ $json.subject }}, Email Format HTML, Retry On Fail on, On Error set to Continue (using error output).
  7. Postgres "Log Success" (Insert into email_logs) on the success output, and "Log Failure" on the error output, followed by an alert.

Best Practices Summary

  1. Validate addresses before sending and check the suppression list
  2. Use templates and escape every value you insert into HTML
  3. Track opens and clicks only if you need them, and treat open rates as approximate because mail clients block or proxy images
  4. Handle bounces and complaints so you stop sending to addresses that reject mail
  5. Pace sending with Loop Over Items and Wait to stay within your provider's limits
  6. Log each send with its status and message ID so failures can be traced
  7. Use fallback channels for critical notifications
  8. Check attachments by type and size, and sanitize file names

Email automation with n8n provides the flexibility to build sophisticated workflows while maintaining the reliability needed for production systems. The key is combining proper error handling with comprehensive logging to ensure deliverability and maintain sender reputation.


From production

In JARVIS, the multi-agent system DeviDevs runs on, outgoing email goes either through the Resend API or natively through Gmail. For cold outreach sent through Resend, the recipient address is checked again on the day of sending, a rule in place since 17 August 2026. Alerts that need an answer (hot leads, deadlines, decisions) go through native Gmail, because sent through Resend to the domain address they did not show up in the founder's Gmail and replies landed in a mailbox nobody read, and a script moves internal mail from no-reply@devidevs.com out of the Promotions tab. For an n8n email workflow, that adds up to two checks: a fresh address check before sending, and a test that internal mail lands where people actually read it.

Official references

Related on this site: AI Automation: Zapier vs Make vs n8n - Which One to Choose?, AI-Powered n8n Workflows: Integration Patterns, n8n CRM Automation: HubSpot & Salesforce Patterns. More articles in the n8n Automation category.

Want AI agents and automations your business can actually run on?

We ship production AI in fixed two-week sprints, then secure them. Book a 30-minute call to scope yours.

Book a Call

Before you book, you can see what we build, how a sprint works, how our pricing works, what we have already built, or write to us directly.

Weekly AI Agents, Automation & Security Digest

How we build AI agents and automations with Claude Code, plus practical AI security, integrations, and platform notes, delivered weekly.

No spam. Unsubscribe anytime.