Hello ${firstName},
Thank you for your order (#${orderId}). Here's a summary of your purchase:
-
${itemsList}
Your order will be processed shortly.
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.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
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:
Step 2: Creating a New Workflow
Now let's create a workflow that includes email notifications:
Step 3: Adding the Send Email Node
Now add the node that will send the email:
Step 4: Configuring the Send Email Node
Configure the Send Email node with the necessary details:
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:
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:
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:
Alternatively, for more complex recipient handling:
Step 8: Error Handling for Email Sending
To handle potential errors when sending emails:
// Expression to check if email was sent successfully
{{$node["Send Email"].json["success"] === true}}
Step 9: Testing Your Email Notification Workflow
Before deploying your workflow, you should test it:
Step 10: Common Email Notification Use Cases
Here are some common scenarios for using email notifications in n8n:
Alert Notifications:
Scheduled Reports:
User Onboarding:
Workflow Status Updates:
Step 11: Advanced Email Personalization
For more sophisticated email notifications, you can use advanced formatting and logic:
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
}
}];
Step 12: Setting Up Email Tracking and Analytics
If you want to track email opens and clicks:
Instead of using basic SMTP, consider using email service providers that offer tracking:
For SendGrid specifically:
Step 13: Troubleshooting Email Sending Issues
If you encounter problems with email sending:
Check Credentials:
Check Email Security Settings:
Review n8n Logs:
Test with a Simple Configuration:
Step 14: Implementing Email Templates System
For consistent email notifications, you can implement a template system:
Create a Credentials & Workflows structure:
Example workflow structure:
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}}
"
}
}
// 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:
Create a "Notification Center" workflow that:
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"
}
}
Step 16: Integration with Other n8n Nodes for Rich Notifications
Enhance your email notifications by combining with other n8n nodes:
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"
}
Step 17: Email Notification Workflow Patterns
Several common workflow patterns can be useful for email notifications:
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
Time
Severity
Message
${alertsHtml}
${moreAlertsMessage}
\`;
return [{
json: {
emailSubject: `System Alert Summary: ${alertSummary.criticalCount} Critical, ${alertSummary.warningCount} Warning`,
emailBody: emailHtml
}
}];
Step 18: Securing Sensitive Information in Email Workflows
When dealing with sensitive data in email notifications:
Use n8n credentials for all sensitive information:
Implement data redaction for sensitive 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
}
}];
Step 19: Setting Up Responsive Email Notifications
To create mobile-friendly email notifications:
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.
// 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:
Implement monitoring for your email workflows:
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'
}
}
}];
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.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.