Q:

How do I send an email with node mailer in node.js?

belongs to collection: Node.js programming Exercises

0

Simple way to send SMTP mail using Node.js

How do I send an email with node mailer in node.js?

In this exercise, you will learn how to send SMTP mail using Node.js. NodeJS is an open source, cross-platform runtime environment for creating server-side and networking applications. It follows a single thread with an event loop that supports multiple concurrent connections.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

These are the step-by-step process to send SMTP 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 the mail.

mailer = require('nodemailer');

smtpProtocol = mailer.createTransport({
    service: "Gmail",
    auth: {
        user: "sender@gmail.com",
        pass: "password"
    }
});

var mailoption = {
    from: "sender@gmail.com",
    to: "receiver@gmail.com",
    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

Finally, the 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 whether the mail was successfully submitted or if an error was reported.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

How to get a local IP address in Node.js?... >>
<< How do you use try catch blocks in node.js?...