Blog /

Send email in Node.JS with Nodemailer using Gmail account

javascript

Send email in Node.JS with Nodemailer using Gmail account

October 21, 20225 minutes
Send email in Node.JS with Nodemailer using Gmail account

Environment & Dependencies

  • Nodemailer is a Node.JS npm module for sending emails.
    This has been the go to solution to most NodeJS developers for email delivery in their applications.
  • Ensure you have NodeJS installed as a run environment.

Prerequisites

• Basic knowledge of JavaScript programming.
• Knowledge Node.JS
• A code editor such as VSCode

Getting started

Go to your project directory

  • Create package.json file

npm init -y

  • install dependencies

npm i nodemailer -s

  • create entry file mailer file & mail-template

touch index.js mailer.js mail-template.js

Project Structure

Project structure

NB: to use ES6 synthax import dependencies, set type: 'module' in the package.json file.

package.json

Implementation

Note: To understand how to navigate the nodemailer codebase and understand how it is implemented, I used askyourcode.

gif


This will save you a lot of time looking for code snippets and implementations online.

mail.js

  • In this file, you will first create your  mail transporter object from nodemailer. This This transporter object make use of the service you are will use for sending the emails, the host and most important an auth object. This object is basically your email id and email password
import nodemailer from "nodemailer";

// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
  service: "gmail",
  host: "smtp.gmail.com",
  port: 587,
  secure: false,
  auth: {
    user: "MAILID@gmail.com",
    pass: "YOUR PASSWORD",
  },
});
  • The next thing is to create a reusable SEND_MAIL function. This function should take two arguments, the mail details and a callback function to handle reponse.
/** create reusable sendmail function 
@params {object} options - mail options (to, subject, text, html)
@params {function} callback - callback function to handle response
*/
const SENDMAIL = async (mailDetails, callback) => {
  try {
    const info = await transporter.sendMail(mailDetails)
    callback(info);
  } catch (error) {
    console.log(error);
  } 
};
  • Export this function to make it accessible by any file you want to issue the SEND_MAIL from.
export default SENDMAIL;

HTML TEMPLATE (mail-template.js)

In most applications, developers are required to send a styled email to meet the Application or company's theme. This can be done in sending mails through nodemailer. You will have to create you own styled HTML TEMPLATE. Below is a sample of template and how to use it

// an email template that can be used with Nodemailer to send emails

const HTML_TEMPLATE = (text) => {
  return `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>NodeMailer Email Template</title>
        <style>
          .container {
            width: 100%;
            height: 100%;
            padding: 20px;
            background-color: #f4f4f4;
          }
          .email {
            width: 80%;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
          }
          .email-header {
            background-color: #333;
            color: #fff;
            padding: 20px;
            text-align: center;
          }
          .email-body {
            padding: 20px;
          }
          .email-footer {
            background-color: #333;
            color: #fff;
            padding: 20px;
            text-align: center;
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="email">
            <div class="email-header">
              <h1>EMAIL HEADER</h1>
            </div>
            <div class="email-body">
              <p>${text}</p>
            </div>
            <div class="email-footer">
              <p>EMAIL FOOTER</p>
            </div>
          </div>
        </div>
      </body>
    </html>
  `;
}

export default HTML_TEMPLATE;

index.js

This is the entry file for sending the email. This can be any file you want to execute your SEND_MAIL command from.
Here, you provide the details of the mail to be sent and finally make use of the SEND_MAIL function from the mailer.js file

  • Sample email details and how to make use of the HTML Template created
import HTML_TEMPLATE from "./mail-template.js";
const message = "Hi there, you were emailed me through nodemailer"
const options = {
    from: "TESTING <sender@gmail.com>", // sender address
    to: "someone@gmail.com", // receiver email
    subject: "Send email in Node.JS with Nodemailer using Gmail account", // Subject line
    text: message
    html: HTML_TEMPLATE(message),
}

NB: The html value can be simply the message text variable if you don't want to use any template.

  • Initiate the SEND_MAIL command using the options object created.
import SENDMAIL from "./mailer.js" 
// send mail with defined transport object and mail options
SENDMAIL(options, (info) => {
    console.log("Email sent successfully");
    console.log("MESSAGE ID: ", info.messageId);
});

Success Output

console
email

Common Errors

On error commonly encounter sending email with nodemailer using gmail is the Application-specific password required error.

Error: Invalid login: 534-5.7.9 Application-specific password required. Learn more at
534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor r27-20020a056402035b00b00459012e5145sm10361434edw.70 - gsmtp
    at SMTPConnection._formatError (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:790:19)
    at SMTPConnection._actionAUTHComplete (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:1542:34)   
    at SMTPConnection.<anonymous> (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:546:26)
    at SMTPConnection._processResponse (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:953:20)       
    at SMTPConnection._onData (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:755:14)
    at TLSSocket.SMTPConnection._onSocketData (PATH\node_modules\nodemailer\lib\smtp-connection\index.js:193:44)
    at TLSSocket.emit (node:events:526:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:228:10) {
  code: 'EAUTH',
  response: '534-5.7.9 Application-specific password required. Learn more at\n' +
    '534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor r27-20020a056402035b00b00459012e5145sm10361434edw.70 - gsmtp',
  responseCode: 534,
  command: 'AUTH PLAIN'
}

This error is due to a security layer google uses to protect your account. You are required to create an App Password to use in this instance.

How to fix this Error

  • Login to your google account.
  • From the sidebar, click on security
  • Scroll down to Signing in with google
  • Click on App Passwords to Generate a new App Password
Idashboard
Generate password


This will generate a 16 character xxxx xxxx xxxx xxxx app-password.
Finally, Replace your actual password in the mailer.js file with the generated password. (don't include the spaces)
This show fix the error!

Feel free to comment below if you encountered any error in implementing it. Let's help each other.

Conclusion

In this article, We only learnt how to implement sending email in NOdeJS with nodemail using Gmail Service
You can use askyourcode to explore the package codebase nodemailer for more ways to improve on the implementation on html templates.

Happy Hacking!

hack

If you find this content helpful, Please Like, comment and share. Follow us for more articles on NodeJS.

Explore other topics