How to send email in Node.Js?

Hey guys,

Today I want to show you how to use nodemailer in node.js to send email.

Node.js has a very active community that are adding new modules daily to the npm (node package module or node package manager), one my favorite module in node.js is nodemailer, this module helps you to send email to any recipient that you want, these are the steps that you need to take in order to use this module.

  1. You must install nodemailer as it is not a core module in node.js
Npm install nodemailer
  1. Create a object from the module.
var nodemailer= require('nodemailer');

 

  1. Create function that sends email and code all the configurations in this function:
Function sendEmail()

{
// you need to create an object that contains all the sender email configuration
var transporter = nodemailer.createTransport({

service: 'Gmail',

auth: {

user: 'your@email.com',

pass: ' you password '

}
});
// You need to create an email content
var mailOptions = {

from: 'janfeshan.mehran@gmail.com',

to: 'info@codingtips.net',

subject: 'Your order is ready',

text: 'Your order is ready for delivery'

html: 'Your order is ready for delivery'

};
//Pass the email content to transporter in order to send email.
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
res.redirect('/');
} else {
console.log('Message Sent: '+info.response);
res.redirect('/');
}
});

}


Categories: Node.Js, Programing tools

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: