DEV Community

Cover image for Send email in Node.JS with Nodemailer using Gmail account
Bentil Shadrack for Documatic

Posted on • Updated on

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 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",
  },
});
Enter fullscreen mode Exit fullscreen mode
  • 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);
  } 
};
Enter fullscreen mode Exit fullscreen mode
  • Export this function to make it accessible by any file you want to issue the SEND_MAIL from.
export default SENDMAIL;
Enter fullscreen mode Exit fullscreen mode

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 your 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;
Enter fullscreen mode Exit fullscreen mode

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),
}
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

Success Output

console

email

Common Errors

One error commonly encountered in 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'
}
Enter fullscreen mode Exit fullscreen mode

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 should 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 nodemailer 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.

Top comments (22)

Collapse
 
hirenprajapatiitpath profile image
Hiren Prajapati

Not working internal style in html page

Collapse
 
qbentil profile image
Bentil Shadrack

Really?
Let me see a snippet of your code

Collapse
 
hirenprajapatiitpath profile image
Hiren Prajapati • Edited

const welcomeEmailTemplate = (fullName) => {

return `

<!DOCTYPE html>









Social Space

<br>
@import url(&quot;<a href="https://fonts.googleapis.com/css2?family=Signika&amp;display=swap%22" rel="nofollow">https://fonts.googleapis.com/css2?family=Signika&amp;amp;display=swap&amp;quot;&lt;/a&gt;);&lt;/p>
<div class="highlight"><pre class="highlight plaintext"><code> :root {
--primary-color: #8344ff;
}

body {
margin: 0;
padding: 0;
font-family: "Signika", sans-serif;
}

h1 {
margin: 0;
color: var(--primary-color);
}

p {
margin: 0;
text-align: justify;
}

a {
text-decoration: none;
color: black;
}
a:hover {
color: var(--primary-color);
}

li::marker {
margin: 0;
}

img {
width: 100%;
max-height: 300px;
margin: 20px 0px;
}

.container {
padding: 25px;
border: 2px solid var(--primary-color);
border-radius: 15px;
}
&lt;/style&gt;
</code></pre></div>
<p></head><br>
<body><br>
<div class="container"><br>
<h1>Your Space for Connecting and Sharing !</h1><br>
<br /><br>
<p>Hey, ${fullName} 👋🏻</p><br>
<img<br>
src="https://res.cloudinary.com/socialspace/image/upload/v1690739392/email-vectors/welcomeVector.svg"&lt;br>
alt="welcome"<br>
/><br>
<p><br>
We are thrilled to extend a warm welcome to you as a new member of our<br>
ever-growing community at<br>
<a style="color: var(--primary-color)" href="">Social Space</a> !<br>
</p><br>
<br /><br>
<p><br>
Your decision to join Social Space brings us one step closer to building<br>
a vibrant online space where users like you can connect with friends,<br>
family, and like-minded individuals, sharing your thoughts, memories,<br>
and experiences with the world.<br>
</p><br>
<br /><br>
<p><br>
Here at Social Space, our mission is to create an inclusive environment<br>
that fosters meaningful interactions, celebrates diversity, and respects<br>
the privacy and security of all our users.<br>
</p><br>
<br /><br>
<p><br>
If you have any questions, concerns, or suggestions, please don&#39;t<br>
hesitate to reach out to our friendly support team at<br>
<a<br>
style="color: var(--primary-color)"<br>
href=""<br>
></a<br>
><br>
We&#39;re here to ensure that your experience on Social Space is as<br>
enjoyable as possible.<br>
</p><br>
<br /><br>
<p><br>
Once again, thank you for choosing <a style="color: var(--primary-color)" href="">Social Space</a>. We are genuinely<br>
excited to have you on board and cannot wait to see the positive impact<br>
you will make within our community.<br>
</p><br>
<br /><br>
<p>Best regards,</p><br>
<br /><br>
<p>The Social Space Team</p><br>
<li><a href="">Yogesh Zala</a></li><br>
<li><a href="">Hiren Prajapati</a></li><br>
</div><br>
</body><br>
</html><br>
`;<br>
};</p>

<p>module.exports = welcomeEmailTemplate;</p>

<p>async function sendWelcomeEmail(email, fullName) {<br>
const mailOptions = {<br>
from: <code>Social Space &lt;${process.env.EMAIL}&gt;</code>,<br>
to: email,<br>
subject: &quot;Welcome to Social Space ! 🖐🏻&quot;,<br>
html: welcomeEmailTemplate(fullName),<br>
};</p>

<p>await sendEmail(mailOptions);<br>
}</p>

Thread Thread
 
qbentil profile image
Bentil Shadrack

The welcomeEmailTemplate looks fine and sould work.

Perhaps the issue will be your implementation. What error do you get?
Send me a mail let's take a close look at it😁

Thread Thread
 
hirenprajapatiitpath profile image
Hiren Prajapati

Thank You for response!
error not show any but styling is not show when i have sent email to someone only show content without styling....

Thread Thread
 
qbentil profile image
Bentil Shadrack • Edited

Oh I see.

Did you use this👇👇

Image description

Thread Thread
 
hirenprajapatiitpath profile image
Hiren Prajapati

Yes, I have used!

Thread Thread
 
hirenprajapatiitpath profile image
Hiren Prajapati

support.google.com/mail/thread/476...
Please check the above Google support link! I think have you idea.

Thread Thread
 
qbentil profile image
Bentil Shadrack

Okay sure

Collapse
 
cyklonehateka profile image
Cyklone Hateka

Very informative

Collapse
 
qbentil profile image
Bentil Shadrack

Thank you

Collapse
 
simvolick profile image
Simvolick

Am I crazy but this doesn't work without getting gmail api key?

Collapse
 
qbentil profile image
Bentil Shadrack

This works fine without any API key.
How are you implementing it?

Collapse
 
amithbhagat profile image
Amit H Bhagat

Thanks for the "Application-specific password required" error resolution

Collapse
 
qbentil profile image
Bentil Shadrack

I am glad it helped

Collapse
 
junaid975a profile image
Junaid Ansari

Hey, i'm using my actual emailId and emailPassword to send mails using nodemailer, with smpt.gmail.com as host, still i'm not able to send the mails and getting the error of false credentials. can anyone please explain me why i'm getting such error?

Collapse
 
junaid975a profile image
Junaid Ansari

`const nodemailer = require("nodemailer");
require("dotenv").config();

const mailSender = async (email, title, body) => {
try{
// mail send krne ke liye transporter use hota h
let transporter = nodemailer.createTransport({
host: process.env.MAIL_HOST,
auth:{
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS,
}
});
// console.log(body);
// console.log(transporter);

    // prepare the email and send
    let info = await transporter.sendMail({
        from: "StudyNotion --by Junaid",
        to: `${email}`,
        subject: `${title}`,
        html: `${body}`
    });

    return info;

} catch(err) {
    console.log("Mail Sender failed.")
    console.log(err.message);
}
Enter fullscreen mode Exit fullscreen mode

}

module.exports = mailSender;`

above is my code snippet for mailSender
please can anyone tell me, where i'm doing it wrong?

Collapse
 
qbentil profile image
Bentil Shadrack

You are not suppose to use your actual gmail password here.

Generate an APP password from your google account and use that instead

Thread Thread
 
vibhatia profile image
Vibhatia

Bro my original mail is sent to the user. Not the 'from' one. Why is it so?

Thread Thread
 
qbentil profile image
Bentil Shadrack

You original email is used for the SMTP config so it is what Gmail uses.

Thread Thread
 
vibhatia profile image
Vibhatia

Is there any way to send an email via the from one?

Collapse
 
vibhatia profile image
Vibhatia

You have to modify the password by going to the security section of gmail.