Want to send simple mail using Gmail. Here is the way

Want to send simple mail using Gmail. Here is the way

send mail using node-mailer and gmail A/C

·

2 min read

Setting up huge mail server for just sending the informing mail on completion of code ?

That's not anyone likes ! ( I Guess.... )

So, today i am sharing snippet for sending mail using gmail account and a node mailer API.

Before stating

setup your mail account :-

Enable the less secure app access of your google account in order to send mail from any custom agent like Node.js.

This is mandatory else where node-mailer will throw authentication-failed exception

Step 1 : install node-mailer and perform basic configuration

I assume you have installed the nodemailer successfully using npm or yarn. I used npm here. If not then paste this into your terminal

npm i node-mailer --save

After this, i will import node-mailer using CommonJS syntax and create the basic configuration object in order to create mail - transporter object. The object will handle the SMTP (Simple Mail Transfer Protocol) and will perform necessary steps to put mail into recipient's inbox

( fav person In my case)


const nodemailer = require("nodemailer");

module.exports = {
    sendMail: function () {
        let mailTransporter = nodemailer.createTransport({
            service: "gmail",
            auth: {
                user:"yourUserName@gmail.com",
                pass: "<SecretPassword",
            },
        });
    },
}

Step 2: create mailer payload : Mailer payload will be consisting of recipient mail, subject of email and related stuff. We can manipulate it just as we want but, i will keep it simple


let mailDetails = {
            from: "yourUserName@gmail.com",
            to: "favPerson@anyDomain.com",
            subject: "You Were Hacked 8)",
            text: "System failure !",
        };

Step 3 : Fire

Execute the sendMail() function with proper args to execute the code . It will send the email and give you result in terminal.


 mailTransporter.sendMail(mailDetails, function (err, data) {
            if (err) {
                console.log("Error Occurs");
            } else {
                console.log("Email sent successfully");
            }
        });

This is it. we successfully sent the mail using gmail and node. This is pretty helpful when informing some once else on the certain recurring events.

Complete code is here ......

mailer.png

Thanks for reading ! make sure to like it !