Send Mail Using Node.js and gmail in few Simple Steps

sudarshan - Apr 27 '21 - - Dev Community

We all know how tedious the stuff gets when we wan't to send mail from any automated system.

For example,

  • ping someone when CRON job at remote VM Executed *
  • Get failure logs of your server in mail* etc

So, today we are going to take a look at how can we send mail from nodejs using just a gmail account and third party library node-mailer


  • Setting up G-mail :-

For sending mail's through your gmail A/C you must allow the " less secure app" access to your google A/C which is done here
a
https://myaccount.google.com/lesssecureapps


Step 1 :- Setting up node-mailer

Install node-mailer using npm or yarn (which is one prefer let me know in comments). I will use npm here because, it comes with node installation

npm i nodemailer 
Enter fullscreen mode Exit fullscreen mode

Step 2 :- Setting up node-mailer and some basic configuration

After installing node-mailer, we have to setup some config's. For sending mail, we are going to use Gmail as a mail service and create a mail transported object. Which internally handles the SMTP (Simple Mail Transfer Protocol) transactions.

const nodemailer = require("nodemailer");

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

Enter fullscreen mode Exit fullscreen mode

Step 3 :- create mail object

Now it's time to create actual mail payload. It will contain of recipient mail address and other stuff like subject and the string which we want to send with the mail. This is the basic payload we can alter the stuff with great flexibility

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

Step 4 :- Send Mail

Now, just hit it. ( I am handling result with callback, you can also use Promise here)

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

That's It. Now, we can send email to anyone with any email address without setting up out own mail server or anything else


Final Thoughts

I hope you all learnt something new from this post. Let me know if anything else I have to write in my next one

Thanks for reading :)

. . . . . . . . . . . . . .