Send Email Using Node and Gmail

You can collect form data from your application and have it sent to your email address using Node.js. Node.js (or “Node”) is an open source server framework that uses Javascript on the server.  In this example I have a website already set up and running in Node.

Nodemailer is a module that gives you the ability to easily send emails in Node. There are some great examples of how to use the Nodemailer module at http://www.nodemailer.com.

Step 1: Client-side setup

For the project we needed a way to collect anonymous feedback from our users, and generate an email containing the feedback. I added a simple html form to our page:

<div class="form-question feedback"> <h5 class="label-text">Feedback</h5> <div class="mssg hidden"> 
Thanks for your feedback! </div> 
<form id="feedback"> <label class="textinput"> 
<span class="label">
<p>Questions? Comments?<br>Send us your thoughts:</p> 
</span>
<span class="field"> 
<input type="text" id="feedback-name" name="feedback-name" placeholder="Name (optional)"> 
</span>
<span class="field"> 
<textarea id="feedback-content" name="feedback-content" rows="4" placeholder="Enter your comments here..."></textarea> 
</span> </label> 
<input class="btn btn-sml" type="submit" value="Send Feedback"> </form> 
</div>

In your client-side Javascript file you handle the form submit and return a message to the screen. This is static html, and in this example I am using jQuery. The jQuery .ajax() method exchanges the data with the Node server, and then displays a success message to the user without reloading the page:

$(document).ready(function() {
 var $form = $('#feedback');
 $form.submit(function(event) {
 var data = {};
 data.name = document.getElementById('feedback-name').value;
 data.content = document.getElementById('feedback-content').value;
 postDataWithCallback('/feedback', data, postSuccess);
 event.preventDefault();
 });
 function postDataWithCallback(url, data, callback) {
 var jsonOut = null;
 $.ajax({
 url: url,
 type: 'POST',
 data: data,
 success: function(json) {
 jsonOut = json;
 }
 }).done(callback);
 }
 function postSuccess() {
 document.getElementsByClassName('mssg')[0].classList.remove('hidden');
 document.getElementById('feedback').classList.add('hidden');
} });

Step 2: Server-side setup

Next, open up your Node application file to set up our post request and create the mail configuration.
This setup requires three modules. Express, Nodemailer, and Body Parser:

npm install express nodemailer 
body-parser --save

After installing these packages and requiring them, the Node application file should look like this:

var express = require('express'); 

var nodemailer = require('nodemailer'); 

var bodyParser = require('body-parser'); 

var app = express();

To handle the HTTP request in Express you need to install this middleware module called body-parser. It extracts the body portion of an incoming request stream, converts it into json, and exposes it on req.body

One last bit of setup for body-parser was to add the middleware layer like this:

app.use(bodyParser.json()); // to support JSON-encoded bodies 
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies 
 extended: true 
}));

Next thing to do was create the post request in Node. We used the post method route in Express. The client- side script will execute the .ajax() method and pass the request to the Node server.

This Node post request function is where we put everything needed to take the submitted form data and send it off in an email. Nodemailer uses SMTP as the main transport for delivering messages. You can use any SMTP service to relay the emails. To use Gmail securely it does require some additional setup. In this example however, I am using Gmail as the SMTP service and have opted to allow non-secure apps to access Gmail by changing the setting here https://myaccount.google.com/lesssecureapps. This is a way of getting around the advanced Google OAuth security setup mentioned previously.
The node application starts to look like this after adding the transporter and mail options:

var express = require('express');
var nodemailer = require('nodemailer');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
 extended: true
}));
app.post('/feedback', function(req, res) {
 var theFeedback = req.body.content;
 var theName = req.body.name;
 var mailOptions = {
 from: 'Website Feedback <no_reply@yourwebsite.com>',
 to: 'you@yourwebsite.com',
 subject: 'Website Feedback',
 text: theFeedback + theName,
 html: theFeedback + '<br><br>' + theName
}; 
var transporter = nodemailer.createTransport({
service: 'gmail',
 auth: {
 user: 'youremail@address.com',
 pass: 'yourpassword'
 }
});
transporter.sendMail(mailOptions, function (err, info) {
 if(err)
 console.log(err)
 else
 console.log(info);
});
res.send('POST request to the homepage')
});

I hope this gives a good overview of how to use Node and Nodemailer to send form data to your email.
Here are some more helpful links:

https://nodemailer.com/about/

https://www.youtube.com/watch?v=CL1sit7wAV4 
https://community.nodemailer.com/using-gmail/


Leave a Reply

Your email address will not be published.