How to Send the Email Using the Gmail SMTP in Node.js

How to Send the Email Using the Gmail SMTP in Node.js

In this node js email sends tutorial, you will learn how you can send the email using the Gmail SMTP in node js. Here you will learn step by step, how you can send email using Gmail SMTP in node js

Overview

In this node js email sends tutorial, you will learn how you can send the email using the Gmail SMTP in node js. Here you will learn step by step, how you can send email using Gmail SMTP in node js

Sending email via Node js is easy. Today we are going to discuss send an email via node js. We will use nodemailermodule and Gmail SMTP to send the email. We will also learn how to send an email with an attachment. So let’s get started with the node js send email with attachment tutorial

First Install Nodemailer

npm install nodemailer

Next, include the nodemailer module in your application

var nodemailer = require('nodemailer');

Configure Gmail SMTP with Nodemailer

The nodemailer needs a transport service using which it can send emails. Use the username and password from your selected email provider to send an email. This tutorial will show you how to use your Gmail account to send an email:

var mail = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '[email protected]',
    pass: 'your-gmail-password'
  }
});

Before sending email using Gmail you have to allow non-secure apps to access Gmail you can do this by going to your Gmail settings here.

Once less secure apps are enabled now nodemailer can use your Gmail for sending the emails.

Sending Email with Gmail SMTP

Now you are ready to send emails from your server.

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Sending Email via Node.js',
  text: 'That was easy!'
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

Send Multiple Recipient At The Same Time

Let’s see, how you can send email to multiple users at the same time

var mailOptions = {
  from: '[email protected]',
  to: '[email protected], [email protected]',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!'
}

Send Simple HTML

To send HTML formatted text in your email, use the “html” property instead of the “text” property:

var mailOptions = {
   from: '[email protected]',
   to: '[email protected], [email protected]',
   subject: 'Sending Email using Node.js',
   html: '# Welcome

That was easy!
'
 }

Send Attachment

attachments option in the message object that contains an array of attachment objects.

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!',
  attachments: [{   // utf-8 string as an attachment
            filename: 'text1.txt',
            content: 'hello world!'
        },
        {   // binary buffer as an attachment
            filename: 'text2.txt',
            content: new Buffer('hello world!','utf-8')
        },
        {   // file on disk as an attachment
            filename: 'text3.txt',
            path: '/path/to/file.txt' // stream this file
        },
        {   // filename and content type is derived from path
            path: '/path/to/file.txt'
        },
        {   // stream as an attachment
            filename: 'text4.txt',
            content: fs.createReadStream('file.txt')
        },
        {   // define custom content type for the attachment
            filename: 'text.bin',
            content: 'hello world!',
            contentType: 'text/plain'
        },
        {   // use URL as an attachment
            filename: 'license.txt',
            path: 'https://raw.github.com/nodemailer/nodemailer/master/LICENSE'
        },
        {   // encoded string as an attachment
            filename: 'text1.txt',
            content: 'aGVsbG8gd29ybGQh',
            encoding: 'base64'
        },
        {   // data uri as an attachment
            path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
        }
    ]
}

After the above changes our app.js the file will look like this

var nodemailer = require('nodemailer');

var mail = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '[email protected]',
    pass: 'your-gmail-password'
  }
});

var mailOptions = {
   from: '[email protected]',
   to: '[email protected], [email protected]',
   subject: 'Sending Email using Node.js',
   html: '# Welcome

That was easy!
' ,
   attachments: [{
       filename: 'text1.txt',
       content: 'hello world!'
   }
}

mail.sendMail(mailOptions, function(error, info){
      if (error) {
        console.log(error);
      } else {
        console.log('Email sent: ' + info.response);
      }
});

Further reading:

Async vs. Sync Handling Concurrency in JS

4 Ways to Empty an Array in Node.js

MongoDB Nodejs Tutorial with Examples

Renaming files using Node.js

Testing Node API with Mocha & Chai

Performing Sentiment Analysis on Tweets from Node.js

Real Time Apps with TypeScript: Integrating Web Sockets, Node & Angular

8 Miraculous Ways to Bolster Your React Apps

MEVN Stack Tutorial With Example From Scratch

node-js javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.