Tag Archives: SMTP

How to send e-mail in Node.js?

In most of real time application we need to send mails for account verification, account recovery, etc. Hence, for Node applications also we need to find some way to send email.

For that Node already have nodemailer module which makes task very easy.

First of all, you will need to install nodemailer and express.js.

npm install nodemailer

npm install express

Then setup your server.js file.

var express=require(‘express’);
var nodemailer = require(“nodemailer”);
var app=express();
app.listen(3000,function(){
console.log(“Express Started on Port 3000″);
});

In your HTML file, you will need add code to hit server.js to send mail. Hence, add following code to your HTML file.

$(document).ready(function(){
var from,to,subject,text;
$(“#send_email”).click(function(){  // send_email is id of button 
to=$(“#to”).val();
subject=$(“#subject”).val();
text=$(“#content”).val();
$(“#message”).text(“Sending E-mail…Please wait”);
$.get(“http://localhost:3000/send”,{to:to,subject:subject,text:text},function(data){
if(data==”sent”)
{
$(“#message”).empty().html(“Email is been sent at “+to+” . Please check inbox !”);

}});

});

});

As we are making request to server we need to handle this in server side also.

app.get(‘/send’,function(req,res){
//code to send e-mail.
});

Now, add nodemailer code,

var smtpTransport = nodemailer.createTransport(“SMTP”,{
service: “Gmail”,
auth: {
user: “yourID@gmail.com”,
pass: “Your Gmail Password”
}
});

Add above code in server.js ,

var smtpTransport = nodemailer.createTransport(“SMTP”,{
service: “Gmail”,
auth: {
user: “yourID@gmail.com”,
pass: “Your G-mail password”
}
});

app.get(‘/’,function(req,res){
res.sendfile(‘index.html’);
});
app.get(‘/send’,function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end(“error”);
}else{
console.log(“Message sent: “ + response.message);
res.end(“sent”);
}
});
});


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.