{"id":105,"date":"2014-07-14T15:28:50","date_gmt":"2014-07-14T09:58:50","guid":{"rendered":"http:\/\/codeforgeek.com\/?p=105"},"modified":"2021-06-19T11:58:55","modified_gmt":"2021-06-19T06:28:55","slug":"send-e-mail-node-js","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/send-e-mail-node-js\/","title":{"rendered":"How to Send e-mail using Node.js"},"content":{"rendered":"<p>In this tutorial i am going to discuss about sending e-mail with Node.js. I have already covered Express.js tutorials and in this tutorial also i am going to use Express.js and <strong>NodeMailer<\/strong> package. In many forums and blogs people used to ask about sending e-mail&#8217;s using Node.js for account verification, password recovery and promotion. So let&#8217;s begin with tutorial and at the end you will have Node application which is able to send e-mail&#8217;s to any one&#8217;s account.<\/p>\n<blockquote><p>Links: Watch live Demo on YouTube <a href=\"https:\/\/www.youtube.com\/watch?v=csroI40tKRI\" target=\"_blank\" rel=\"noopener\">here<\/a> and Download it from Github <a href=\"https:\/\/codeload.github.com\/codeforgeek\/Node-Mailer\/zip\/master\" target=\"_blank\" rel=\"noopener\">here<\/a>.<\/p><\/blockquote>\n<h2>What we are Building ?<\/h2>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-106\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/mailer.png\" alt=\"How to send e-mail in node.js\" width=\"700\" height=\"357\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/mailer.png 700w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/mailer-300x153.png 300w\" sizes=\"(max-width: 700px) 100vw, 700px\" \/><\/p>\n<p>Create <strong>package.json <\/strong>file and keep it in any folder. Put the below code in it.<\/p>\n<div class=\"file_name\"><strong>package.json<\/strong><\/div>\n<p><code><br \/>\n{<br \/>\n  \"name\": \"email-node\",<br \/>\n  \"version\": \"1.0.0\",<br \/>\n  \"dependencies\": {<br \/>\n    \"nodemailer\": \"latest\",<br \/>\n    \"express\": \"latest\"<br \/>\n  }<br \/>\n}<\/p>\n<p><\/code><\/p>\n<p>Once done. Switch to that folder using Command prompt or Terminal and type <strong>npm install. <\/strong>It will download and install the dependencies our project need. After completion you will able to see <strong>node_modules <\/strong>folder in your project directory.<\/p>\n<h2>Implementing Server.js:<\/h2>\n<p>Let&#8217;s begin with creation of our Server file. Paste code shown below in file named as <strong>&#8220;Server.js&#8221;.<\/strong><\/p>\n<div class=\"file_name\"><strong>Server.js<\/strong><\/div>\n<p><code lang=\"javascript\"><br \/>\nvar express=require('express');<br \/>\nvar nodemailer = require(\"nodemailer\");<br \/>\nvar app=express();<br \/>\napp.listen(3000,function(){<br \/>\nconsole.log(\"Express Started on Port 3000\");<br \/>\n});<br \/>\n<\/code><br \/>\nThis is basic block of our app. If you run it in Terminal you will see console message. Now let&#8217;s add some routing logic to tell our app what is supposed to do when Request comes from browser. Add these code just above the <b>app.listen<\/b> line.<br \/>\n<code lang=\"javascript\"><br \/>\napp.get('\/',function(req,res){<br \/>\nres.sendfile('index.html');<br \/>\n});<br \/>\n<\/code><br \/>\nNow when you try to open your app from browser, it will return the index.html as response. Let me show you basic snippet of HTML code.<\/p>\n<div class=\"file_name\"><strong>index.html<\/strong><\/div>\n<p><code lang=\"html\"><\/p>\n<div id=\"container\">\n<div><\/div>\n<p>Node.JS Email application<\/p>\n<div>\n<h1>Mailer In Node.JS<\/h1>\n<p><input id=\"to\" type=\"text\" placeholder=\"Enter E-mail ID where you want to send\" \/><br \/>\n<input id=\"subject\" type=\"text\" placeholder=\"Write Subject\" \/><br \/>\n<textarea id=\"content\" cols=\"40\" rows=\"5\" placeholder=\"Write what you want to send\"><\/textarea><br \/>\n<button id=\"send_email\">Send Email<\/button><br \/>\n<span id=\"message\"><\/span>\n<\/div>\n<p><\/code><br \/>\nNow next thing to do is to call our Server from HTML page when user hit on &#8216;Send Email&#8217; Button. To do so at client end i am using jQuery. Here is code snippet of jQuery inside HTML page only.<\/p>\n<div class=\"file_name\"><strong>index.html<\/strong><\/div>\n<p><code lang=\"javascript\"><br \/>\n<script>\n$(document).ready(function(){\n\tvar from,to,subject,text;\n\t$(\"#send_email\").click(function(){\t\t\n\t\tto=$(\"#to\").val();\n\t\tsubject=$(\"#subject\").val();\n\t\ttext=$(\"#content\").val();\n\t\t$(\"#message\").text(\"Sending E-mail...Please wait\");\n\t\t$.get(\"http:\/\/localhost:3000\/send\",{to:to,subject:subject,text:text},function(data){\n\t\tif(data==\"sent\")\n\t\t{\n\t\t\t$(\"#message\").empty().html(\"<\/p>\n<p>Email is been sent at \"+to+\" . Please check inbox!<\/p>\n<p>\");\n\t\t}<\/p>\n<p>});\n\t});\n});\n<\/script><br \/>\n<\/code><br \/>\n<b>Notice :<\/b> At $.get we are calling our app with &#8216;\/send&#8217; as handler so now we have to add router in our Server.js file in order to deal with this request. So let&#8217;s add some code to handle this route request. Add these code just below of app.get(&#8216;\/&#8217;) line.<b> File name : Server.js <\/b><\/p>\n<div class=\"file_name\"><strong>Server.js<\/strong><\/div>\n<p><code lang=\"javascript\"><br \/>\napp.get('\/send',function(req,res){<br \/>\n\/\/code to send e-mail.<br \/>\n\/\/Will be shown soon.<br \/>\n});<br \/>\n<\/code><\/p>\n<h2>Adding NodeMailer code:<\/h2>\n<p>Okay we are almost there, now we have to handle the Mail system. First of all we have to Define Mail transport System (SMTP) so that from that E-mail box our e-mail will be sent. For ease, you can add your Gmail account and password. Add this code just in <b>Server.js<\/b> just below the &#8216;var app=express()&#8217; line.<br \/>\n<code lang=\"javascript\"><br \/>\nvar smtpTransport = nodemailer.createTransport({<br \/>\n    service: \"gmail\",<br \/>\n    host: \"smtp.gmail.com\",<br \/>\n    auth: {<br \/>\n        user: \"\",<br \/>\n        pass: \"\"<br \/>\n    }<br \/>\n});<br \/>\n<\/code><br \/>\nWe will use this Object to send e-mail. Our app design is when user click on &#8216;Send email&#8217; Button then only e-mail should be sent, and we have did that part in &#8220;<b>app.get(&#8216;\/send&#8217;)<\/b>&#8221; router. So in that block only paste the code shown below.<br \/>\n<code lang=\"javascript\"><br \/>\nvar mailOptions={<br \/>\n   to : req.query.to,<br \/>\n   subject : req.query.subject,<br \/>\n   text : req.query.text<br \/>\n}<br \/>\nconsole.log(mailOptions);<br \/>\nsmtpTransport.sendMail(mailOptions, function(error, response){<br \/>\nif(error){<br \/>\nconsole.log(error);<br \/>\nres.end(\"error\");<br \/>\n}else{<br \/>\nconsole.log(\"Message sent: \" + response.message);<br \/>\nres.end(\"sent\");<br \/>\n}<br \/>\n});<br \/>\n<\/code><br \/>\nIn above code we have read GET variables send from HTML page and we have call &#8220;<b>sendMail()<b>&#8221; function using Transport object we have created above. In case there is any confusion here is a complete Server.js file.<\/b><\/b><\/p>\n<div class=\"file_name\"><strong>Server.js<\/strong><\/div>\n<p><code lang=\"javascript\"><\/p>\n<p>var express=require('express');<br \/>\nvar nodemailer = require(\"nodemailer\");<br \/>\nvar app=express();<br \/>\n\/*<br \/>\n\tHere we are configuring our SMTP Server details.<br \/>\n\tSTMP is mail server which is responsible for sending and recieving email.<br \/>\n*\/<br \/>\nvar smtpTransport = nodemailer.createTransport({<br \/>\n    service: \"gmail\",<br \/>\n    host: \"smtp.gmail.com\",<br \/>\n    auth: {<br \/>\n        user: \"\",<br \/>\n        pass: \"\"<br \/>\n    }<br \/>\n});<br \/>\n\/*------------------SMTP Over-----------------------------*\/<\/p>\n<p>\/*------------------Routing Started ------------------------*\/<\/p>\n<p>app.get('\/',function(req,res){<br \/>\n\tres.sendfile('index.html');<br \/>\n});<br \/>\napp.get('\/send',function(req,res){<br \/>\n\tvar mailOptions={<br \/>\n\t\tto : req.query.to,<br \/>\n\t\tsubject : req.query.subject,<br \/>\n\t\ttext : req.query.text<br \/>\n\t}<br \/>\n\tconsole.log(mailOptions);<br \/>\n\tsmtpTransport.sendMail(mailOptions, function(error, response){<br \/>\n   \t if(error){<br \/>\n        \tconsole.log(error);<br \/>\n\t\tres.end(\"error\");<br \/>\n\t }else{<br \/>\n        \tconsole.log(\"Message sent: \" + response.message);<br \/>\n\t\tres.end(\"sent\");<br \/>\n    \t }<br \/>\n});<br \/>\n});<\/p>\n<p>\/*--------------------Routing Over----------------------------*\/<\/p>\n<p>app.listen(3000,function(){<br \/>\n\tconsole.log(\"Express Started on Port 3000\");<br \/>\n});<br \/>\n<\/code><br \/>\nAnd this is how HTML page looks like with all styles and JS.<\/p>\n<div class=\"file_name\"><strong>index.html<\/strong><\/div>\n<p><code lang=\"html\"><br \/>\n<html><br \/>\n<head><br \/>\n<title>Node.JS Email application<\/title><br \/>\n<script src=\"\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.11.1\/jquery.min.js\"><\/script><script>\/\/ <![CDATA[\n$(document).ready(function(){\n\tvar from,to,subject,text;\n\t$(\"#send_email\").click(function(){\t\t\n\t\tto=$(\"#to\").val();\n\t\tsubject=$(\"#subject\").val();\n\t\ttext=$(\"#content\").val();\n\t\t$(\"#message\").text(\"Sending E-mail...Please wait\");\n\t\t$.get(\"http:\/\/localhost:3000\/send\",{to:to,subject:subject,text:text},function(data){\n\t\tif(data==\"sent\")\n\t\t{\n\t\t\t$(\"#message\").empty().html(\"\n\nEmail is been sent at \"+to+\" . Please check inbox!\n\n\");\n\t\t}\n\n});\n\t});\n});\n<\/script>\n<\/head>\n<body>\n\n\n<div id=\"container\">\n\n\n<h1>Mailer In Node.JS<\/h1>\n\n\n<input id=\"to\" type=\"text\" placeholder=\"Enter E-mail ID where you want to send\" \/>\n<input id=\"subject\" type=\"text\" placeholder=\"Write Subject\" \/>\n<textarea id=\"content\" cols=\"40\" rows=\"5\" placeholder=\"Write what you want to send\"><\/textarea>\n<button id=\"send_email\">Send Email<\/button>\n<span id=\"message\"><\/span>\n<\/div>\n\n\n<\/div>\n\n\n<\/code>\nThat's it for now. If you have any queries do let me know in comments.\n\n\n<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial i am going to discuss about sending e-mail with Node.js. I have already covered Express.js tutorials and in this tutorial also i am going to use Express.js and NodeMailer package. In many forums and blogs people used to ask about sending e-mail&#8217;s using Node.js for account verification, password recovery and promotion. So [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":109,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[22,14,18],"tags":[],"class_list":["post-105","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-express","category-nodejs","category-tutorial"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/email-banner.png",840,400,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/email-banner-150x150.png",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/email-banner-300x143.png",300,143,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/email-banner-768x366.png",768,366,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/email-banner.png",840,400,false],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/email-banner.png",840,400,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2014\/07\/email-banner.png",840,400,false]},"uagb_author_info":{"display_name":"Shahid","author_link":"https:\/\/codeforgeek.com\/author\/shahid\/"},"uagb_comment_info":0,"uagb_excerpt":"In this tutorial i am going to discuss about sending e-mail with Node.js. I have already covered Express.js tutorials and in this tutorial also i am going to use Express.js and NodeMailer package. In many forums and blogs people used to ask about sending e-mail&#8217;s using Node.js for account verification, password recovery and promotion. So&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/105","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=105"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/105\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/109"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=105"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=105"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=105"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}