Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Add Data in JSON File using Node.js ?
Next article icon

How to send Attachments and Email using nodemailer in Node.js ?

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

For this purpose, we will use a package called nodemailer. It is a module that makes email sending pretty easy. For using it, you will need to install by using the following command: 

$ npm install nodemailer

Features of nodemailer module: 

  • It has zero dependencies and heavy security.
  • You can use it hassle-free whether it is Azure or Windows box.
  • It also comes with Custom Plugin support for manipulating messages.

In order to send an email, create a file named index.js and write down the following code: 

Filename: index.js 

javascript




const nodemailer = require("nodemailer");
 
let sender = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'your_password'
    }
});
 
let mail = {
    from: "[email protected]",
    to: "receiver'[email protected]",
    subject: "Sending Email using Node.js",
    text: "That was easy!"
};
 
sender.sendMail(mail, function (error, info) {
    if (error) {
        console.log(error);
    } else {
        console.log("Email sent successfully: "
            + info.response);
    }
});
 
 

Steps to run this program: In order to run this file, just Git Bash into your working directory and type the following command: 

$ nodemon index.js

If you don’t have Nodemon installed then just run the following command: 

$ node index.js

To double-check its working you can go to the receiver’s mail and you will get the following mail as shown below:  


What if you have multiple receivers? 

Well in that case just add the below code to your mail function: 

to: '[email protected], [email protected]'

What if you want to send HTML-formatted text to the receiver? 

Well in that case just add the below code to your mail function: 

html: "<h1>GeeksforGeeks</h1><p>I love geeksforgeeks</p>"

What if you want to send an attachment to the receiver? 

Well in that case just add the below code to your mail function: 

attachments: [     {         filename: 'mailtrap.png',         path: __dirname + '/mailtrap.png',         cid: 'uniq-mailtrap.png'     } ]

The final index.js file looks like this: 

Filename: index.js 

javascript




let nodemailer = require("nodemailer");
 
let sender = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'your_password'
    }
});
 
let mail = {
    from: '[email protected]',
    to:
        '[email protected], [email protected]',
    subject: 'Sending Email using Node.js',
    text: 'That was easy!',
    html:
        '<h1>GeeksforGeeks</h1>< p > I love geeksforgeeks</p>',
attachments: [
    {
        filename: 'mailtrap.png',
        path: __dirname + '/mailtrap.png',
        cid: 'uniq-mailtrap.png'
    }
]
};
 
sender.sendMail(mail, function (error, info) {
    if (error) {
        console.log(error);
    } else {
        console.log('Email sent successfully: '
            + info.response);
    }
});
 
 


Next Article
How to Add Data in JSON File using Node.js ?

M

MohdArsalan
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-Misc

Similar Reads

  • How to send email with Nodemailer using Gmail account in Node ?
    Nodemailer is an npm module that allows you to send emails easily from the backend. In this article, we will cover the steps to send email using a Gmail account with the help of nodemailer. Prerequisites:NPM and NodeJSExpressJSApproach To send email with Nodemailer using gmail Import the nodemailer
    3 min read
  • How to Send Email using Mailgun API in Node.js ?
    Sending an email is an essential part of any project and it can be achieved by using Mailgun API. It is very popular for sending emails. Features of Mailgun: .  It is easy to get started and easy to use.It is a widely used and popular module for sending emails.Mails can also be scheduled. Installati
    2 min read
  • How to Add Data in JSON File using Node.js ?
    JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article. Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
    4 min read
  • How to write e-mails in HTML and send it using Gmail ?
    In this article, we are going to learn that how users can write e-mails in HTML format and send them using Gmail. However, Gmail doesn't offer an HTML editor still we can send HTML templates in an e-mail using some tools and methods. Many people need to send an e-mail with HTML templates to others.
    3 min read
  • How to add authentication in file uploads using Node.js ?
    There are multiple ways to upload files and apply authentications to them. The easiest way to do so is to use a node module called multer. We can add authentication by restricting users on file uploads such as they can upload only pdf and the file size should be less than 1 Mb. There are many module
    3 min read
  • How to Build Note Taking Application using Node.js?
    Building a note-taking application using Node.js involves several steps, from setting up the server to managing the application logic and user interface. This guide will walk you through the process of creating a simple note-taking application using Node.js, Express, and a few other key technologies
    6 min read
  • How to Generate or Send JSON Data at the Server Side using Node.js ?
    In modern web development, JSON (JavaScript Object Notation) is the most commonly used format for data exchange between a server and a client. Node.js, with its powerful runtime and extensive ecosystem, provides robust tools for generating and sending JSON data on the server side. This guide will wa
    3 min read
  • How to Send Email using NodeJS?
    Sending emails programmatically is a common requirement in many applications, especially for user notifications, order confirmations, password resets, and newsletters. In this article, we will learn how to build a simple email-sending system using NodeJS. We will use Nodemailer, a popular module for
    5 min read
  • Sending bulk emails in Node.js using SendGrid API
    What is SendGrid API? SendGrid is a platform for sending transactional and marketing emails to the customers. It provides scalability, reliability, and deliverability which is an important issue for an organization.Benefits of using SendGrid API: If you are using Nodemailer with Gmail then you can s
    2 min read
  • How to Send Response From Server to Client using Node.js and Express.js ?
    In web development, sending responses from the server to the client is a fundamental aspect of building interactive and dynamic applications. Express.js, a popular framework for Node.js, simplifies this process, making it easy to send various types of responses such as HTML, JSON, files, and more. T
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences