Simple way to send SMTP mail using Node.js

In this article, you will learn how to send SMTP mail using Node.js.

SMTP stands for Simple Mail Transfer Protocol. SMTP is a TCP/IP protocol of internet standard for electronic mail transmission from one user to another. In this, mail is pushed to the destination mail server or either POP or IMAP are used to retrieve the mail. For this, we need SMTP Server details SERVICE, USERNAME and PASSWORD.

These are the steps to send mail -

STEP 1: Install nodemailer package.

Open command prompt, Go to the directory of your project and write the following command to install nodemailer.

npm install nodemailer

STEP 2: Include nodemailer and set your SMTP mail server credentials, recipient information and send mail.


mailer = require('nodemailer');

smtpProtocol = mailer.createTransport({
    service: "Gmail",
    auth: {
        user: "This email address is being protected from spambots. You need JavaScript enabled to view it.",
        pass: "password"
    }
});

var mailoption = {
    from: "This email address is being protected from spambots. You need JavaScript enabled to view it.",
    to: "This email address is being protected from spambots. You need JavaScript enabled to view it.",
    subject: "Test Mail",
    html: 'Good Morning!'
}

smtpProtocol.sendMail(mailoption, function(err, response){
    if(err) {
        console.log(err);
    } 
    console.log('Message Sent' + response.message);
    smtpProtocol.close();
});

In the above example, smtpProtocol is a mail configuration object and mailer.createTransport() is a transport service that includes mail service, username and password.

The mailoption is another configuration object that contain other details -

  • from: Sender email address
  • to: Receiver email address
  • subject: Subject of the mail
  • html: Message body

At last, sendMail() function is responsible to send mail. It contains two parameters - mailoptions object that we had set earlier and a callback function. The callback function will be called when mail is sent to notify the user either mail is submitted successfully or report an error.





Read more articles


General Knowledge



Learn Popular Language