• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Sending Emails with nodemailer in Node.js: A Step-by-Step Tutorial

  • June 21, 2023
  • CODE OF GEEKS
  • 0
Node.js Emails
Node.js Emails

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

Tags: email attachmentsemail integrationemail templatesKeywords: Node.js emailMailgunnodemailerSendGridsending emails with Node.jsSMTP server
  • Previous Express.js: Simplify Web Application Development with Node.js
  • Next Node.js Buffers: A Comprehensive Guide to Efficient Data Manipulation

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.