How to use Nodemailer

Nodemailer is a module offered by Node.js that sends emails from the server. It is easy to use and prioritizes user account security to offer a good and trustworthy experience. It requires a service to work on, e.g., Gmail, which we can specify in the transporter.has the configuration options that define how Nodemailer should send the emails.

Features of Nodemailer

Nodemailer stands out because it offers various features to offer.

  • It is platform-independent.

  • It is a single module with zero dependencies, making it easy to code and interpret.

  • It uses TLS/STARTTLSA protocol command used to inform the email server that the email client wants to upgrade from an insecure connection to a secure one. to ensure email is delivered in a secure way.

  • It supports Unicode international character encoding standard to allow the use of any characters in the email.

Generating custom password

We need to generate a custom password when providing email credentials to the program because giving a real password can compromise account security. To do that, follow these simple steps.

Step 1: Open the Google Account, which will be used as the sender's Gmail address, and go to security.

Note: The custom keys are different for each account and should be generated carefully.

Step 2: Open the 2-Step verification in the security if you have enabled it. Enabling the verification notification whenever the password is used somewhere to avoid any misuse.

Open Google Account and follow the steps.
Open Google Account and follow the steps.

Step 3: Click "App passwords" and generate a custom password.

Open app passwords to create password.
Open app passwords to create password.

Step 4: Provide a name for the app. You can name it whatever you want and then click generate to receive a 16-digit code.

Generate a custom password.
1 of 3

Now that we know what Nodemailer is and have learned how to generate a custom password, let's implement our understanding and write a code for it.

Required imports

Before writing the code, import and, if needed, install the following modules to access their functionalities.

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const readline = require('readline');
  • express: to provide features for handling HTTP requests, routing, and middleware.

  • bodyParser: to extract and make data available in the req.body object from the request's body.

  • nodemailer: to create a transport object and send emails using the specified email credentials.

  • readline: to create a readline interface and take the user's Gmail ID and password as input.

Example code

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const readline = require('readline');

const app = express();

//Create a readline interface
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

app.use(bodyParser.urlencoded({ extended: true }));

// Prompt the user for the email and password
rl.question('Enter your Gmail email ID: ', (senderEmail) => {
  rl.question('Enter your password: ', (pass) => {
    rl.close();
    console.log('Server is running on port 8080');

    const transporter = nodemailer.createTransport({
     service: 'gmail',
     auth: {
      user: senderEmail,
      pass: pass,
     },
    });

    app.post('/submit', (req, res) => {
    const { email_, sub_, text_ } = req.body;

    const mailOptions = {
      from: senderEmail,
      to: email_, 
      subject: sub_,
      text: text_
    };

    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        console.log(error);
        res.send('<p>Error occurred while sending the email</p>');
      } else {
        console.log('Email sent: ' + info.response);
        res.send('<p>Email sent successfully!</p>');
      }
    });
   });
  });
});

app.get('/', (req, res) => {
  res.send(`
<form method="post" action="/submit" style="background-color: #d9f0fa; padding: 10px; border-radius: 5px;">
    <label for="email_" style="display: block; margin-bottom: 5px; font-weight: bold;">Email ID:</label>
    <input type="email" id="email_" name="email_" required style="width: 60%; padding: 8px; margin-bottom: 12px; border: 1px solid #ccc; border-radius: 3px;">
    <br>
    <label for="sub_" style="display: block; margin-bottom: 5px; font-weight: bold;">Subject Txt:</label>
    <input type="text" id="sub_" name="sub_" required style="width: 60%; padding: 8px; margin-bottom: 12px; border: 1px solid #ccc; border-radius: 3px;">
    <br>
    <label for="text_" style="display: block; margin-bottom: 5px; font-weight: bold;">Message:</label>
    <textarea id="text_" name="text_" required style="width: 60%; padding: 8px; margin-bottom: 12px; border: 1px solid #ccc; border-radius: 3px; resize: vertical; height: 150px;"></textarea>
    <br>
    <input type="submit" value="Submit" style="background-color: #194d63; color: #fff; padding:10px; border: none; border-radius: 4px;">
  </form>
  `);
});

app.listen(8080, () => {

});
Code for sending email using nodemailer.

Code explanation

  • Lines 1–4: Import the necessary modules.

  • Line 6: Create the app variable and assign an Express instance to it using express().

  • Lines 9–11: Use readline.createInterface to create the interface and prompt the user for input.

  • Line 14: Add the bodyParser to the Express code to parse the URL-encoded data from POST requests.

  • Lines 17–20: Take the email and password as input using rl the readline interface and print a message to show that the server is running.

  • Lines 22–26: Use creatTransport() from the nodemailer module to create a transport object and specify the service and credentials that will be used to access the account.

  • Lines 30–37: Create a POST request on the /submit endpoint that sets the inputted sender's email, recipient email, subject, and email message when the submit button is clicked.

  • Lines 40–46: Call the sendmail() method from the transporter and pass the mailOptions to it. If the email is sent successfully, print a success message; otherwise, print an error message.

  • Lines 53–66: Create a GET request on the default path / and display a simple form that takes the recipient's email, subject, and email message as input.

  • Line 70: Use listen() and specify the port, i.e., 8080 to inform the server from where to process the requests.

Code output

Once the credentials are inputted, and the server starts running successfully, a form opens on port 8080.

Step 1: Enter the following details to send a customized email.

  • Recipient's email address.

  • A precise subject of the email.

  • A customized text message, which is to be sent via email.

The interface on port 8080 when server is running.
The interface on port 8080 when server is running.

Step 2: Click the submit button and wait; the success or error message is printed on the screen.

Step 3: If a success message is printed, check the sent messages of the Gmail account used as the sender's email and notice that the email has been sent to the recipient email address from that account.

Here is a short video that shows the output once the email credentials are given as console input and the form is submitted.

Summary

Nodemailer is a friendly Node.js module that is used to send emails using server. It ensures account security and efficient email delivery. You can use nodemailer and set a hard-corded email in it so every time you run the code, that email is sent without composing it again and again.

Note: Now let's learn how to embed image using Nodemailer.

Common query

Question

Is it essential to generate a custom password every time?

Show Answer

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved