• Home
  • About Me
  • Twitter Trends
  • YoutTube Trends
  • Google Trends
  • Age Calculator
  • Public Holidays
  • Fancy Fonts
  • Privacy Policy
  • Contact Me

iamrohit.in

My Public Notebook

Skip to content
Menu
  • Lab
  • Tools
    • YouTube Tags Generator
    • IP Location Finder
    • English 2 Hindi Typing
    • Cron Generator
    • Image Color Picker
    • QR Code Generator
    • Base64 Decoder
    • Base64 Encoder
    • Age Calculator
  • Free Submission
    • Business Listing Directories
    • Directory Submission Sites
    • Social Bookmarking Sites
    • Classified Sites
      • India
      • Australia
      • Canada
      • United Kingdom
      • United States
    • Article Submission Sites
    • Press Release Sites List
    • PDF / DOC / PPT Submission Sites
    • Web 2.0 Submission Sites
    • RSS Feed Submission Sites List
    • Search Engine Submission Sites List
    • Forum Submission Sites List
    • Profile Creation Sites
    • Pinging Submission Sites
    • Wiki Submission Sites List
    • Image Sharing Sites
    • Question and Answer Sites List
    • Video Submission Sites
    • PDF Submission Sites List
    • Document Sharing Sites
    • Profile Creation Sites List
    • Podcast Submission
  • jQuery Plugins
    • Accordion
    • Barcode
    • Calendar
    • Clock
    • Countdown
    • Character Count
    • ColorPicker
    • Data Grid
    • DatePicker
    • Date Time
    • EU Cookie Law
    • Fileuploader
    • Form Validation
    • Icon Picker
    • Image Slider
    • image Crop
    • Image Zoom
    • Inputmask
    • Loading
    • Mega Menu
    • Menu
    • Multiselect
    • Multi-Step Form
    • News Ticker
    • Notification
    • Photo Gallery
    • QR Code
    • TimePicker
    • Tooltip
  • COUPONS

How to send email in nodejs

by adminPosted onMarch 7, 2016March 7, 2016

Today we are going to learn how to send email in node.js, If we are developer then each phase of development we need to implement email functionality in our website.

So in this post you’ll se how to send email in nodejs with SMTP and without SMTP , there is very cool module “nodemailer” available in npm to send email with smtp.
You can learn more about this module form here http://www.nodemailer.com


Lets start step by step…

Make sure that you have already setup nodejs environment with express framework.

Node Emailer
Node Emailer

Step-1: Create package.json file in root directory of your application.

package.json

{
  "name": "NodeJs-Emailer",
  "version": "0.0.1",
  "description": "NodeJs email form to send email using nodejs",
  "dependencies": {
    "nodemailer": "~0.7.0",
    "express": "~3.4.0",
    "body-parser": "~1.13.1"
  }
}

Step-2: Create index.html file and paste below html code & save it.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Send email in nodejs</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="panel panel-primary" style="width:50%;margin:0 auto; margin-top:10%">
<div class="panel-heading"><h3>Email Form In Node.Js</h3></div>
<div class="panel-body" style="height:40%; text-align:center;" >
<p class="bg-info" id="msg"></p>
 <form class="form-horizontal" role="form" id="emailForm" method="post">
  <div class="form-group">
    <label class="control-label col-sm-2" for="email">Email:</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" name="email" placeholder="Enter email" required="required">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-2" for="subject">Subject:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" name="subject" placeholder="Enter subject" required="required">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-2" for="description">Description:</label>
    <div class="col-sm-10">
      <textarea class="form-control" name="description" placeholder="Enter Description"></textarea>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button id="send" class="btn btn-primary btn-lg" type="button">
         <span class="glyphicon glyphicon-send" ></span> Send
      </button>
    </div>
  </div>
</form>
</div>
</div>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
$(function(){
  var fullUrl =  location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
    $("#send").click(function(){      
      var formData = $("#emailForm").serialize();
      $("#msg").text("Email sending Please wait..");
                $.ajax({
                url: fullUrl+'/send',
                type: 'POST',
                data: formData,
                success: function(result) {
                                 $("#msg").empty().text(result);
                         },
                error: function(e) {
                                 $("#msg").empty().text("There is some error to send email, Error code:"+e.status +", Error message:"+e.statusText);
                       },
                dataType: "html",
                timeout: 60000
            });
    });
});
</script>
</body>
</html>

Step-3: Create app.js file in your folder and paste below server side code in app.js file.
Here i am using Hotmial SMTP to send emails you can use other mail server smtp like Gmail, Yahoo as your need.




Note: Currently app.js configured for simple email without SMTP. If you want to use SMTP then remove comment from SMTP section in app.js try to run app.js again.

app.js

/*
* Author: Rohit Kumar
* Date: 24-06-2015
* Website: iamrohit.in
* App Name: Node Emailer
* Description: NodeJs script to send emails
*/
var http=require('http');
var express=require('express');
var nodemailer = require("nodemailer");
var bodyParser = require('body-parser')
var app=express();
var port = Number(process.env.PORT || 5000);
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({
  extended: true
}));
 
// Home page
app.get('/',function(req,res){
    res.sendfile('index.html');
});
 
// sending mail function
app.post('/send', function(req, res){
if(req.body.email == "" || req.body.subject == "") {
  res.send("Error: Email & Subject should not blank");
  return false;
}
// Sending Email Without SMTP
nodemailer.mail({
    from: "Node Emailer ✔ <[email protected]>", // sender address
    to: req.body.email, // list of receivers
    subject: req.body.subject+" ✔", // Subject line
    //text: "Hello world ✔", // plaintext body
    html: "<b>"+req.body.description+"</b>" // html body
});
res.send("Email has been sent successfully");
 
   // Sending Emails with SMTP, Configuring SMTP settings
 
    /*var smtpTransport = nodemailer.createTransport("SMTP",{
             host: "smtp.gmail.com", // hostname
    secureConnection: true, // use SSL
    port: 465, // port for secure SMTP
            auth: {
                 user: "[email protected]",
                 pass: "['YourHotmailPassword']"
            }
        });
        var mailOptions = {
            from: "Node Emailer ✔ <[email protected]>", // sender address
            to: req.body.email, // list of receivers
            subject: req.body.subject+" ✔", // Subject line
            //text: "Hello world ✔", // plaintext body
            html: "<b>"+req.body.description+"</b>" // html body
        }
        smtpTransport.sendMail(mailOptions, function(error, response){
        if(error){
             res.send("Email could not sent due to error: "+error);
        }else{
             res.send("Email has been sent successfully");
        } 
    }); */
});
 
// Starting server
var server = http.createServer(app).listen(port, function() {
console.log("Listening on " + port);
});

Step-5: Run

$ sudo npm install

on your terminal this will read all dependencies from package.json file and install them in your directory.

Step-6: Now finally open the terminal run command

$ node app.js

now you’ll see output like

Listening on 5000

this shows every thing is fine.
Finally time to check working url
http://your-hoostname:5000 hit on your browser if you are on localhost http://localhost:5000

You can see working demo by click on demo button and also download source code by download button.

Cheers Keep Coding 🙂

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Google+ (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Reddit (Opens in new window)

Related

Posted in: Express, NodeJsTags: Create email module in nodejs, How to create email form in node js, How to send email in node.js without smtp, How to send email using nodejs, How to send server email with Node.js, How to send smtp email in nodejs, Responsive HTML Email Form with Node.js, Send email with nodejs, Sending email from nodejs, Sending Email using G-Mail SMTP in Node.js

Published by admin

View all posts by admin

Post navigation

Prev How to publish nodejs application on web free..!!
Next Export data in excel using php and cakephp
HostArmada Affordable Cloud SSD Shared Hosting

Subscribe to My Public NoteBook

Enter your email address to subscribe my public notebook and receive notifications of new posts by email.

Join 22,611 other subscribers

Categories

  • Angular.js (63)
  • Bootstrap (54)
  • CakePHP (9)
  • CSS & CSS3 (257)
  • Express (10)
  • Hosting (9)
  • Interview Question and Answer (15)
  • Jquery & Javascript (519)
  • Kali Linux (9)
  • Make Money Online (9)
  • MYSQL (29)
  • NodeJs (22)
  • Offers & Deals (2)
  • Others (11)
  • PHP (145)
  • ReactJs (3)
  • Security Tips (16)
  • SEO (43)
  • Tailwind CSS (1)
  • Tips & Tricks (52)
  • Ubuntu (26)
  • VueJs (49)
  • WordPress (26)
DigitalOcean Referral Badge
Privacy & Cookies: This site uses cookies.
To find out more, as well as how to remove or block these, see here: Our Cookie Policy
© Copyright 2022 – iamrohit.in
Allium Theme by TemplateLens ⋅ Powered by WordPress