/n8n-tutorials

How to send email notifications in n8n?

Learn how to send email notifications in n8n using the Send Email node. Set up SMTP, create workflows, add dynamic content, attachments, and handle errors for automated alerts.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to send email notifications in n8n?

To send email notifications in n8n, you need to use the Send Email node, which allows you to configure the sender, recipient, subject, and content of your emails. This can be integrated into your workflow to automatically send notifications based on certain triggers or conditions.

 

Step 1: Setting Up Email Service Provider in n8n

 

Before sending emails, you need to configure an email service provider in n8n. n8n supports various email services like SMTP, SendGrid, Mailgun, etc.

For this tutorial, we'll focus on setting up SMTP as it's the most versatile option:

  1. Navigate to the "Settings" section in your n8n instance
  2. Click on "Credentials"
  3. Click on "New Credential"
  4. Select "SMTP" from the dropdown menu
  5. Fill in the following details:
    • User: Your email address
    • Password: Your email password or app password
    • Host: SMTP server address (e.g., smtp.gmail.com for Gmail)
    • Port: SMTP port (usually 465 for SSL or 587 for TLS)
    • SSL/TLS: Select the appropriate security protocol
  6. Click "Save" to store your credentials

 

Step 2: Creating a New Workflow

 

Now let's create a workflow that includes email notifications:

  1. Go to the n8n workflow editor
  2. Click "Create New Workflow"
  3. Name your workflow (e.g., "Email Notification System")
  4. Add a trigger node to start your workflow. This could be:
    • Schedule trigger: To send emails at specific times
    • Webhook: To send emails when a webhook is called
    • Any other trigger that fits your use case

 

Step 3: Adding the Send Email Node

 

Now add the node that will send the email:

  1. Click the "+" button to add a new node
  2. Search for "Send Email" in the nodes panel
  3. Select the "Send Email" node
  4. Connect it to your trigger node

 

Step 4: Configuring the Send Email Node

 

Configure the Send Email node with the necessary details:

  1. Click on the "Send Email" node to open its settings
  2. In the "Credentials" dropdown, select the SMTP credentials you created earlier
  3. Fill in the following fields:
    • From Email: Your sender email address
    • From Name: The name that will appear as the sender (optional)
    • To Email: The recipient's email address
    • Subject: Email subject line
    • Email Format: Select either "Text" or "HTML"
    • Text: If you selected "Text" format, enter your message here
    • HTML: If you selected "HTML" format, enter your HTML-formatted message here

Here's an example configuration:


// Example configuration values
From Email: [email protected]
From Name: System Notifications
To Email: [email protected]
Subject: Important System Notification
Email Format: HTML
HTML: 

System Alert

This is an automated notification from your system.

 

Step 5: Using Dynamic Data in Email Content

 

To make your emails more useful, you'll often want to include dynamic data from previous nodes:

  1. In the Send Email node configuration, you can use expressions to include data
  2. Click on any field (like Subject or HTML)
  3. Click the gears icon to open the Expression Editor
  4. Use the variable selector to choose data from previous nodes

Example of dynamic content in the HTML field:


System Alert: {{$node["Webhook"].json["type"]}}

Alert Details: {{$node["Webhook"].json["message"]}}

Time: {{$now.format("YYYY-MM-DD HH:mm:ss")}}

 

Step 6: Adding Attachments to Emails

 

If you need to include attachments in your email notifications:

  1. In the Send Email node configuration, enable the "Attachments" section
  2. Set "Add Attachments" to "Yes"
  3. Click "Add Attachment" to create a new attachment entry
  4. Configure each attachment with:
    • Binary Property: The binary data to include (e.g., from a previous node)
    • File Name: Name of the attachment file

For example, to attach a file from a previous HTTP Request node:


// Example attachment configuration
Binary Property: data
File Name: report.pdf

 

Step 7: Sending Emails to Multiple Recipients

 

To send the same email to multiple recipients:

  1. In the "To Email" field, enter multiple email addresses separated by commas
  2. Example: recipient1@example.com, recipient2@example.com, recipient3@example.com

Alternatively, for more complex recipient handling:

  1. Enable the "Send to Multiple Recipients" option
  2. Select how you want to handle Cc and Bcc recipients
  3. Configure the To, Cc, and Bcc fields as needed

 

Step 8: Error Handling for Email Sending

 

To handle potential errors when sending emails:

  1. Add an "IF" node after your Send Email node
  2. Configure it to check if the email was sent successfully:

// Expression to check if email was sent successfully
{{$node["Send Email"].json["success"] === true}}
  1. Add nodes to handle both success and error paths
  2. For the error path, you might want to log the error or try an alternative notification method

 

Step 9: Testing Your Email Notification Workflow

 

Before deploying your workflow, you should test it:

  1. Click "Execute Workflow" in the n8n interface
  2. Check the execution results to see if the email was sent successfully
  3. Verify that the email was received at the destination address
  4. Check that the content and formatting appear as expected

 

Step 10: Common Email Notification Use Cases

 

Here are some common scenarios for using email notifications in n8n:

  1. Alert Notifications:

    • Monitor a system and send emails when issues are detected
    • Example: Send an email when a website goes down
  2. Scheduled Reports:

    • Use the Schedule trigger to send regular reports
    • Example: Send a weekly summary of business metrics
  3. User Onboarding:

    • Send welcome emails when new users sign up
    • Example: When a webhook receives a new user registration
  4. Workflow Status Updates:

    • Send emails about the status of automated processes
    • Example: Notify when a data import is complete

 

Step 11: Advanced Email Personalization

 

For more sophisticated email notifications, you can use advanced formatting and logic:

  1. Using HTML templates:
    • Create an HTML template with placeholders for dynamic content
    • Use a Function node to populate the template with data

Example Function node to create HTML email content:


// Function node code to generate HTML email content
const firstName = items[0].json.user.firstName;
const orderId = items[0].json.order.id;
const orderItems = items[0].json.order.items;

let itemsList = '';
for (const item of orderItems) {
  itemsList += `
  • ${item.quantity} x ${item.name} - $${item.price.toFixed(2)}
  • `; } const htmlContent = \`

    Order Confirmation

    Hello ${firstName},

    Thank you for your order (#${orderId}). Here's a summary of your purchase:

      ${itemsList}

    Your order will be processed shortly.

    \`; return [{ json: { htmlContent: htmlContent } }];
    1. Then, in the Send Email node:
      • Set Email Format to "HTML"
      • Use an expression to reference the HTML content: {{$node["Generate HTML Content"].json["htmlContent"]}}

     

    Step 12: Setting Up Email Tracking and Analytics

     

    If you want to track email opens and clicks:

    1. Instead of using basic SMTP, consider using email service providers that offer tracking:

      • Set up Mailchimp, SendGrid, or Mailgun credentials in n8n
      • Use their respective nodes instead of the generic Send Email node
    2. For SendGrid specifically:

      • Add the SendGrid node to your workflow
      • Configure it with your API key
      • Enable tracking options in the node settings

     

    Step 13: Troubleshooting Email Sending Issues

     

    If you encounter problems with email sending:

    1. Check Credentials:

      • Verify that your SMTP credentials are correct
      • Ensure that your email provider allows SMTP access (Gmail requires App Passwords)
    2. Check Email Security Settings:

      • Some email providers block automated emails
      • Check your email provider's security settings
    3. Review n8n Logs:

      • Check the execution logs for detailed error messages
      • Look for connection timeouts, authentication failures, or rate limit errors
    4. Test with a Simple Configuration:

      • Create a minimal email configuration without attachments or complex formatting
      • If this works, gradually add complexity to identify the problematic component

     

    Step 14: Implementing Email Templates System

     

    For consistent email notifications, you can implement a template system:

    1. Create a Credentials & Workflows structure:

      • Store email templates in a database or as JSON files
      • Create a Function node that retrieves and populates templates
    2. Example workflow structure:

      • Trigger Node → Get Template → Populate Template → Send Email
    3. Template storage implementation using n8n variables:

    
    // In n8n settings, create workflow variables for templates
    // Example template variable:
    
    {
      "welcome\_email": {
        "subject": "Welcome to {{company\_name}}!",
        "body": "

    Welcome, {{user_name}}!

    We're excited to have you join {{company_name}}.

    " }, "alert\_email": { "subject": "ALERT: {{alert\_type}} detected", "body": "

    System Alert

    An issue of type {{alert\_type}} was detected at {{time}}.

    Details: {{details}}

    " } }
    1. Function node to retrieve and populate a template:
    
    // Function to get and populate email template
    const templateName = items[0].json.templateName; // e.g., "welcome\_email"
    const templates = $vars.emailTemplates;
    
    // Get the requested template
    const template = templates[templateName];
    if (!template) {
      throw new Error(`Template "${templateName}" not found!`);
    }
    
    // Populate template variables
    let subject = template.subject;
    let body = template.body;
    
    // Replace all placeholders with actual values
    const data = items[0].json.data;
    for (const [key, value] of Object.entries(data)) {
      const placeholder = new RegExp(`{{${key}}}`, 'g');
      subject = subject.replace(placeholder, value);
      body = body.replace(placeholder, value);
    }
    
    return [{
      json: {
        subject: subject,
        body: body
      }
    }];
    

     

    Step 15: Creating an Email Notification Center

     

    For more advanced applications, you can create a centralized email notification system:

    1. Create a "Notification Center" workflow that:

      • Receives notification requests via a webhook
      • Processes and prioritizes notifications
      • Formats and sends emails based on notification type
    2. Example webhook payload to trigger an email notification:

    
    {
      "notificationType": "alert",
      "priority": "high",
      "recipients": ["[email protected]", "[email protected]"],
      "data": {
        "alert\_type": "Server Outage",
        "time": "2023-06-15 14:32:05",
        "details": "The main application server is not responding to health checks",
        "systemId": "prod-app-01"
      }
    }
    
    1. Implementation steps:
      • Create a webhook node to receive notification requests
      • Add a Switch node to route different notification types
      • For each type, use a template system as described in Step 14
      • Add priority handling to send urgent notifications immediately
      • Implement recipient management based on notification type and context

     

    Step 16: Integration with Other n8n Nodes for Rich Notifications

     

    Enhance your email notifications by combining with other n8n nodes:

    1. Generate charts and graphs for email reports:
      • Use the HTTP Request node to call a chart generation API like QuickChart
      • Include the generated chart image in your email

    Example HTTP Request node configuration for chart generation:

    
    // HTTP Request node to generate a chart
    {
      "url": "https://quickchart.io/chart",
      "method": "POST",
      "sendBody": true,
      "bodyContentType": "json",
      "body": {
        "width": 500,
        "height": 300,
        "format": "png",
        "chart": {
          "type": "bar",
          "data": {
            "labels": ["January", "February", "March", "April", "May"],
            "datasets": [{
              "label": "Sales",
              "data": [65, 59, 80, 81, 56]
            }]
          }
        }
      },
      "responseFormat": "file"
    }
    
    1. Include this chart in your email:
      • Add the Send Email node after the HTTP Request node
      • Set "Add Attachments" to "Yes"
      • Use the binary data from the HTTP Request as the attachment
      • Or embed the image directly in HTML email using base64 encoding

     

    Step 17: Email Notification Workflow Patterns

     

    Several common workflow patterns can be useful for email notifications:

    1. Aggregation Pattern: Collect multiple events before sending a single email
      • Use the "Split In Batches" node to group events
      • Aggregate data in a Function node
      • Send a single email with the aggregated information

    Example Function node for aggregating alert data:

    
    // Function to aggregate multiple alerts into a single email
    let alertSummary = {
      criticalCount: 0,
      warningCount: 0,
      infoCount: 0,
      alerts: []
    };
    
    // Process all incoming items (alerts)
    for (const item of items) {
      const alert = item.json;
      
      // Count by severity
      if (alert.severity === 'critical') alertSummary.criticalCount++;
      else if (alert.severity === 'warning') alertSummary.warningCount++;
      else if (alert.severity === 'info') alertSummary.infoCount++;
      
      // Add to detailed list (limit to 10 for readability)
      if (alertSummary.alerts.length < 10) {
        alertSummary.alerts.push({
          time: alert.timestamp,
          message: alert.message,
          severity: alert.severity
        });
      }
    }
    
    // Generate HTML alert list
    let alertsHtml = '';
    for (const alert of alertSummary.alerts) {
      const severityColor = alert.severity === 'critical' ? '#ff0000' : 
                            (alert.severity === 'warning' ? '#ffaa00' : '#0088ff');
      
      alertsHtml += \`
        
          ${alert.time}
          ${alert.severity.toUpperCase()}
          ${alert.message}
        
      \`;
    }
    
    // If there are more alerts than we're showing in detail
    let moreAlertsMessage = '';
    const totalAlerts = alertSummary.criticalCount + alertSummary.warningCount + alertSummary.infoCount;
    if (totalAlerts > 10) {
      moreAlertsMessage = `

    Plus ${totalAlerts - 10} more alerts not shown in detail.

    `; } // Create the email HTML const emailHtml = \`

    System Alert Summary

    In the last hour, we detected:

    • ${alertSummary.criticalCount} critical alerts
    • ${alertSummary.warningCount} warning alerts
    • ${alertSummary.infoCount} informational alerts

    Recent Alerts

    ${alertsHtml}
    Time Severity Message
    ${moreAlertsMessage} \`; return [{ json: { emailSubject: `System Alert Summary: ${alertSummary.criticalCount} Critical, ${alertSummary.warningCount} Warning`, emailBody: emailHtml } }];
    1. Throttling Pattern: Limit email frequency to avoid overwhelming recipients
      • Use the "Cron" node to schedule digest emails instead of immediate notifications
      • Store events in a database or file between digests
      • Send one comprehensive email at scheduled intervals

     

    Step 18: Securing Sensitive Information in Email Workflows

     

    When dealing with sensitive data in email notifications:

    1. Use n8n credentials for all sensitive information:

      • Store email server credentials securely
      • Never hardcode passwords or API keys in workflow nodes
    2. Implement data redaction for sensitive information:

      • Add a Function node before the Send Email node to redact sensitive data
      • Replace sensitive parts with placeholders or partial information

    Example Function node for data redaction:

    
    // Function to redact sensitive information before sending in email
    function redactCreditCard(cardNumber) {
      if (!cardNumber) return '';
      // Keep only last 4 digits
      return '**_-_**-\*\*\*\*-' + cardNumber.slice(-4);
    }
    
    function redactEmail(email) {
      if (!email) return '';
      const parts = email.split('@');
      if (parts.length !== 2) return email;
      // Show only first character of the local part
      return parts[0].charAt(0) + '\*\*\*\*@' + parts[1];
    }
    
    // Process the incoming data
    const userData = items[0].json.userData;
    const redactedData = {
      ...userData,
      creditCard: redactCreditCard(userData.creditCard),
      email: redactEmail(userData.email),
      ssn: userData.ssn ? '\***-**-' + userData.ssn.slice(-4) : '',
      // Add more redaction as needed
    };
    
    return [{
      json: {
        originalData: items[0].json,
        redactedData: redactedData
      }
    }];
    
    1. For the Send Email node, use the redacted data:
      • Reference fields from the redacted data object instead of original data
      • Implement controls on who receives what level of detail in notifications

     

    Step 19: Setting Up Responsive Email Notifications

     

    To create mobile-friendly email notifications:

    1. Use responsive HTML templates:
      • Include proper meta tags and responsive CSS
      • Test your emails on multiple devices and email clients

    Example responsive email template:

    
    
    
    
      
      
      Your Notification
      
    
    
      

    {{notification\_title}}

    Hello {{recipient\_name}},

    {{notification\_message}}

    {{action_text}}

    If you have any questions, please contact our support team.

    1. Use a Function node to populate this template:
    
    // Function to populate responsive email template
    const currentYear = new Date().getFullYear();
    const data = items[0].json;
    
    // Replace template placeholders
    let template = $vars.responsiveEmailTemplate;
    template = template.replace(/{{notification\_title}}/g, data.title)
                      .replace(/{{recipient\_name}}/g, data.recipientName)
                      .replace(/{{notification\_message}}/g, data.message)
                      .replace(/{{action\_url}}/g, data.actionUrl)
                      .replace(/{{action\_text}}/g, data.actionText)
                      .replace(/{{company\_name}}/g, data.companyName)
                      .replace(/{{current\_year}}/g, currentYear);
    
    return [{
      json: {
        emailSubject: data.title,
        emailHtml: template
      }
    }];
    

     

    Step 20: Monitoring and Maintaining Email Notification Systems

     

    To ensure your email notification system remains reliable:

    1. Implement monitoring for your email workflows:

      • Create a workflow that checks for failed email notifications
      • Set up alerts when email sending fails (through alternative channels)
      • Log all email activity for auditing purposes
    2. Set up a logging system:

    
    // Function node to log email activity
    const emailData = {
      timestamp: new Date().toISOString(),
      recipient: items[0].json.to,
      subject: items[0].json.subject,
      status: items[0].json.success ? 'sent' : 'failed',
      error: items[0].json.error || null
    };
    
    // Log to database, file, or external service
    // Example: Append to a JSON file using Write Binary File node
    return [{
      json: {
        logEntry: emailData
      },
      binary: {
        data: {
          data: Buffer.from(JSON.stringify(emailData) + '\n'),
          mimeType: 'application/json'
        }
      }
    }];
    
    1. Regular maintenance tasks:
      • Review email delivery statistics periodically
      • Check for email templates that may need updating
      • Monitor email sending reputation with your provider
      • Update SMTP credentials when passwords change

    By following these steps, you'll have a comprehensive and reliable email notification system built in n8n that can handle a wide range of notification needs for your organization or personal projects.

    Want to explore opportunities to work with us?

    Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

    Book a Free Consultation

    Client trust and success are our top priorities

    When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

    Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

    CPO, Praction - Arkady Sokolov

    May 2, 2023

    Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

    Co-Founder, Arc - Donald Muir

    Dec 27, 2022

    Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

    Co-CEO, Grantify - Mat Westergreen-Thorne

    Oct 15, 2022

    Rapid Dev is an excellent developer for no-code and low-code solutions.
    We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

    Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

    May 1, 2024 

    Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
    This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

    Production Manager, Media Production Company - Samantha Fekete

    Sep 23, 2022