How To Send Mail Using NodeJS

In this article, we will learn how to send mail using nodejs.

–First, we need to install npm i nodemailer package.

  • it’s used for sending mail.

then import this module to your file:

const nodemailer = require("nodemailer");

-write the below code in your file:

app.post('/mail-sent', (req, res) => {
    let body = req.body
    let me = body.me   //sender id
    let pass = body.password   //sender password
    let to = body.to   // receiver id
    let sub = body.sub   //subject name
    let text = body.text   //body text
    var transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: me,
            pass: pass
        }
    });

    var mailOptions = {
        from: me,
        to: to,
        subject: sub,
        text: text,
    };

    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.log(error);
        } else {
            console.log('Email sent: ' + info.response);
            res.status(200).send({
                success: true,
                msg: "mail sent"
            })
        }
    });
})

-let’s test the  mail-sent api:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories