Skip to content
the poor coder

nodemailer gmail example

Poor Man
Published
Reading time
3 min read
On this page

Nodemailer Gmail Example#

If you are looking for a way to send emails using Node.js, Nodemailer is a great option. With Nodemailer, you can send emails using various email providers, including Gmail. In this post, I will show you how to send an email using Nodemailer and Gmail.

Prerequisites#

  • Node.js installed on your machine
  • A Gmail account

Step 1: Install Nodemailer#

You can install Nodemailer using npm. Open your terminal and run the following command:

Bash
$ npm install nodemailer

Step 2: Set up Gmail account#

You need to allow third-party access to your Gmail account in order to send emails using Nodemailer. To do this:

  • Go to your Google Account settings
  • Click on Security
  • Scroll down and turn on "Less secure app access"

Step 3: Write the code#

Create a new file called "index.js". Add the following code:

JavaScript
const nodemailer = require('nodemailer');

async function sendEmail() {
  let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'your_email@gmail.com',
      pass: 'your_password'
    }
  });

  let info = await transporter.sendMail({
    from: 'your_email@gmail.com',
    to: 'recipient_email@example.com',
    subject: 'Test Email',
    text: 'This is a test email sent using Nodemailer and Gmail.'
  });

  console.log('Message sent: %s', info.messageId);
}

sendEmail().catch(console.error);

Replace "your_email@gmail.com" and "your_password" with your Gmail credentials. Replace "recipient_email@example.com" with the email address of the recipient.

Step 4: Run the code#

Open your terminal and navigate to the directory where "index.js" is located. Run the following command:

Bash
$ node index.js

If everything is set up correctly, you should see a message in your terminal saying that the message has been sent.

Alternative Method: OAuth2 Authentication#

You can also use OAuth2 authentication to send emails using Nodemailer and Gmail. This method is more secure and recommended by Google. Here are the steps:

  • Create a new project in the Google Cloud Console
  • Enable the Gmail API for the project
  • Create credentials for the project (choose "OAuth client ID")
  • Download the credentials file and rename it to "credentials.json"
  • Add the following code to "index.js":
JavaScript
const nodemailer = require('nodemailer');
const { google } = require('googleapis');
const OAuth2 = google.auth.OAuth2;

const oauth2Client = new OAuth2(
  'YOUR_CLIENT_ID',
  'YOUR_CLIENT_SECRET',
  'https://developers.google.com/oauthplayground'
);

oauth2Client.setCredentials({
  refresh_token: 'YOUR_REFRESH_TOKEN'
});

async function sendEmail() {
  const accessToken = await oauth2Client.getAccessToken();

  let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      type: 'OAuth2',
      user: 'your_email@gmail.com',
      clientId: 'YOUR_CLIENT_ID',
      clientSecret: 'YOUR_CLIENT_SECRET',
      refreshToken: 'YOUR_REFRESH_TOKEN',
      accessToken: accessToken
    }
  });

  let info = await transporter.sendMail({
    from: 'your_email@gmail.com',
    to: 'recipient_email@example.com',
    subject: 'Test Email',
    text: 'This is a test email sent using Nodemailer and Gmail.'
  });

  console.log('Message sent: %s', info.messageId);
}

sendEmail().catch(console.error);

Replace "YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", and "YOUR_REFRESH_TOKEN" with the values from your credentials file. Replace "your_email@gmail.com" and "recipient_email@example.com" with the appropriate email addresses.

Run the code using the same command as before:

Bash
$ node index.js

If everything is set up correctly, you should see a message in your terminal saying that the message has been sent.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC