
Sending emails programmatically is a common requirement in many web applications. In this tutorial, we will explore how to send emails using Node.js, a popular runtime environment for server-side JavaScript.
By following this step-by-step guide, you will learn various techniques for sending emails, integrating with SMTP servers, handling attachments, and utilizing popular libraries and services.
Let’s get started !
Setting Up the Project
Install Node.js and initialize a new project using the following commands:
mkdir nodejs-email-tutorial
cd nodejs-email-tutorial
npm init -y
Install the required dependencies, such as Nodemailer and dotenv:
npm install nodemailer dotenv
Sending Basic Emails
Create a new file named sendEmail.js and add the following code:
require('dotenv').config();
const nodemailer = require('nodemailer');
// Create a transporter object with SMTP settings
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: process.env.SMTP_SECURE === 'true',
auth: {
user: process.env.SMTP_USERNAME,
pass: process.env.SMTP_PASSWORD,
},
});
// Set up email data
const mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Hello from Node.js',
text: 'This is a test email sent from Node.js.',
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error occurred:', error);
} else {
console.log('Email sent:', info.response);
}
});
CODE BREAK
require('dotenv').config();: This line loads the environment variables from a .env file into the Node.js environment. It allows you to securely store sensitive information like SMTP credentials.
const nodemailer = require('nodemailer');: This line imports the Nodemailer library, which provides functionality for sending emails.
const transporter = nodemailer.createTransport({ ... });: This creates a transporter object that is responsible for sending the email. It is configured with the SMTP settings provided via environment variables (e.g., SMTP host, port, secure connection, and authentication details).
const mailOptions = { ... };: This defines the email data, including the sender, recipient, subject, and text content of the email.
transporter.sendMail(mailOptions, (error, info) => { ... });: This line sends the email using the sendMail method of the transporter object. It takes the mailOptions object and a callback function as parameters. The callback function handles the response from the email sending operation, checking for errors and logging the success message or error details accordingly.
Sending Emails with Attachments
To send an email with an attachment, modify the mailOptions object in the previous code as follows:
const mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Hello from Node.js',
text: 'This is a test email with an attachment.',
attachments: [
{
filename: 'document.pdf',
path: '/path/to/document.pdf',
},
],
};
Using Email Templates
To send an email using a template, install a templating engine like Handlebars:
npm install handlebars
Create an email template file named template.hbs with the following content:
<!DOCTYPE html>
<html>
<body>
<h1>Hello, {{ name }}!</h1>
<p>This is a test email template.</p>
</body>
</html>
.hbs is a handlebars template file.
Modify the sendEmail.js file to use the template:
const handlebars = require('handlebars');
const fs = require('fs');
// Read the template file
const templateSource = fs.readFileSync('template.hbs', 'utf8');
const template = handlebars.compile(templateSource);
// Set up email data
const mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Hello from Node.js',
html: template({ name: 'John Doe' }),
};
Integrating with SMTP Servers
Create a .env file in the project directory and add the following SMTP configuration:
SMTP_HOST=smtp.mailtrap.io
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USERNAME=your-smtp-username
SMTP_PASSWORD=your-smtp-password
Update the sendEmail.js file to load the environment variables:
require('dotenv').config();
Handling Email Responses and Delivery Status
Nodemailer provides event-driven functionality to track email delivery status. Add the following code after the sendMail function call:
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error occurred:', error);
} else {
console.log('Email sent:', info.response);
}
});
transporter.on('sent', (message) => {
console.log('Email sent successfully:', message);
});
transporter.on('error', (error) => {
console.error('Error occurred during sending:', error);
});
Also, if you want to integrate with a third-party email delivery service like Mailgun, follow their respective documentation for setup and configuration. You just need to modify ‘transporter’ object.
Congratulations! You have successfully learned how to send emails with Node.js using various techniques and libraries.
Keywords to search: Keywords: Node.js email, sending emails with Node.js, email integration, SMTP server, email attachments, email templates, nodemailer, SendGrid, Mailgun
