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 the nodemailer package.

Open the 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 contains other details -

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

At last, sendMail() function is responsible for sending 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 the mail is submitted successfully or report an error.





Related Articles

Python send mail to multiple recipients using SMTP server
PHP code to send email using SMTP
Python send HTML email with attachment
PHP Sending HTML form data to an Email
Retrieve Emails from Gmail using PHP IMAP
Django send email on contact form submission
Simple star rating system using PHP, jQuery and Ajax
jQuery File upload progress bar with file size validation
JavaScript display PDF in the browser using Ajax call
jQuery loop over JSON result after AJAX Success
Rating system PHP
jQuery File upload progress bar with file size validation
Print section of page using javascript
Submit a form data without page refresh using PHP, Ajax and Javascript




Read more articles


General Knowledge



Learn Popular Language