How To Send email In NodeJs

Today, Laravelcode share with you how to send mail in nodejs. in current position nodejs is more and more use. many things we have done with nodejs without write huge code.

In this tutorials we are share with you email sending in nodejs. becasue in any application we must be required a mail sending functionality.

We are write here very simple code for mail sending in nodejs. you can mail send in nodejs using nodemailer

Step : 1 Install nodemailer

We are first need to install nodemailer package for mail sending in nodejs. run followign command for install it.


npm install nodemailer@0.7.1

Step : 2 Create mail.js file

No create mail.js file in your project root directory and simple put following code into it.


var nodemailer = require('nodemailer');

// Create a SMTP transport object
var transport = nodemailer.createTransport("SMTP", {
        service: 'Gmail',
        auth: {
            user: "laravelcode@gmail.com",
            pass: "laravelcode"
        }
    });

console.log('SMTP Configured');

// Message object
var message = {

    // sender info
    from: 'Sender Name <laravelcode@gmail.com>s',

    // Comma separated list of recipients
    to: '"Receiver Name" <laravelcode@gmail.com>s',

    // Subject of the message
    subject: 'How to send mail in nodejs ✔', 

    // plaintext body
    text: 'Hello, everyone!',

    // HTML body
    html:'<p>s<b>sLook this</b>s  <img src=""/>s</p>s'+
         '<p>sHere i am send my picture attachment:<br/>s</p>s'
};

console.log('Sending Mail');
transport.sendMail(message, function(error){
  if(error){
      console.log('Error occured');
      console.log(error.message);
      return;
  }
  console.log('Message sent successfully!');

  // if you don't want to use this transport object anymore, uncomment following line
  //transport.close(); // close the connection pool
});

Now we are ready to run our example so run bellow command ro quick run:


node mail.js

If you face any problem then please write a comment or give some suggestions for improvement. Thanks...

 Prev post

Next post