How to Send Emails Using Nodejs

How to send Emails using NodeJS

This article will show you How to send Emails using NodeJS.

If you’re using NodeJS this far, It’s too obvious that Node is already installed on your system. Still if not, it’s the first prerequisites before starting any NodeJS project. You may download it from their official nodejs.org (opens in a new tab) Website.

How to send Emails using NodeJS

While you’re working with Full stack applications, scenarios are quite different, You need to accept data dynamically & on that basis we got some Node packages to help fasten the process.

User Input

In the initial stage, we’ll be accepting data from the user through a form. Use ‘Name‘ entity in the Html form and ‘req.body.name‘ in the backend to receive user input.

Make sure you’re not using an HTML file, instead convert the extension to ‘.ejs‘, along with that install the respective packages as well. Embedded JS will help work with dynamic JS snippets in a faster and more efficient way.

<div class="container">
  <form action="" method="POST">
    <input name="profile" type="text" placeholder="Username" />
    <input name="notifyingNumber" type="number" />
    <input name="email" type="email" placeholder="Enter Email" />
    <input type="submit" placeholder="Submit" />
  </form>
</div>

Installing Packages

Run the given command in the terminal to install Nodemailer, as well as a template renderer like EJS or EmbeddedJS to your node project.

npm install nodemailer ejs

Dependencies

Create a file named ‘app.js‘, starting off by including Nodemailer.

const nodemailer = require("nodemailer");

To use any templates with Nodemailer EJS as well as HandleBars can be used, we’ll use EJS by setting the view engine. Here we’re using ExpressJS hence we can easily use ‘app.set’ to assign the view engine.

app.set("view engine", "ejs");

However, if Handlebars is what you’re opting for your dynamic frontend template to use with Nodemailer, I have a separate tutorial on that. Make sure to check timestamps from the video to look for that specific frontend guide.

Grabbing user Input

The below function will send the user-submitted data to the backend and assign them to respective variables.

 app.post('/', (req, res)=> {
    var profileUrl = req.body.profile;
    var profileEmail = req.body.email;
    var notifyNumber = parseInt(req.body.notifyingNumber);
})

Working with Nodemailer is pretty simple and straightforward.

  • Create a MailOptions Object
  • Create a Transporter object
  • Use the Transporter.sendMail method
function sendmail() {
  const mailOptions = {
    from: "👻 Your ID",
    to: "Email of recipient",
    subject: `New post from ${showProfileName}`,
    html: `You have received Notification from the user post Tracking system`
  };
  const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: process.env.GMAIL_LOGIN,
      pass: process.env.PASSWORD
    }
  });
  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      console.log(err);
    }
    console.log("Email Sent Successfully");
  });
}

The ${showProfileName} from the above snippet is a Javascript variable used in the project which dynamically varies from user to user. To learn more about how to use databases and manage user-based variables, watch the above Youtube tutorial.

Talking of process.env.GMAIL_LOGIN is the environment variable that stores confidential keys locally.

Enabling Access

In order to send email using Gmail as a service from third-party apps like the NodeJS Mailer app, you need to enable the ‘Allow less secure apps’ option in Gmail. To do so, log in to your Gmail account and navigate to “https://myaccount.google.com/lesssecureapps” (opens in a new tab) and enable it.

enable less secure apps for coding

This process is one of the crucial ones in the ‘How to send Emails using NodeJS’ tutorial, as keeping this disabled for your Gmail account might not let the Node app access the SMTP from your backend server.

Related: How to Create a Stock Price API

Conclusion

This was a complete in-depth guide to ‘How to send Emails using NodeJS’, I really hope this tutorial has helped you in a way. Soon we’ll be publishing another article on sending Emails via Vanilla JS and a third-party SMTP script.

The article is composed keeping in mind that you have a basic knowledge of programming in NodeJS, still if you’re struggling to understand anything just comment below and I’ll reply to you as soon as possible.

To get new updates on that topic with exciting brute content on programming and geeky pieces of stuff, stay tuned.

IndGeek provides solutions in the software field, and is a hub for ultimate Tech Knowledge.