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 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 the EmbeddedJS, body-parser as well as Nodemailer to your node project.

npm install nodemailer ejs body-parser

Dependencies

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

const nodemailer = require('nodemailer')
const bodyParser = require('body-parser')

To make the Front end work, 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');

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: process.env.GMAIL_LOGIN,
        to: process.env.RECEIVER,
        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');
    });
}

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” 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 Email 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.

Sharing Is Caring:
Editorial Staff

An aspiring BTech Electronics and Communication student, obsessed with Coding, Gadgets, Blogging, & Digital Marketing.

Leave a Comment