Send an Email with Node and Express

After writing an API to send emails from a front end contact form, I would like to share with you a tutorial on how you can write your own API to use with your front end.

For this we will be writing the API in Javascript (Node and Express) and using nodemailer npm package which is fairly simple to use.

Lets get started!

Create our project directory

 API
¦   package.json
¦   server.js
+---server
    ¦
    +---routes
        ¦   api.js 

Install dependencies:

npm init
npm install express --save  
npm install nodemailer --save 

Configure our entry point (server.js) with the following:


var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
var api = require('./server/routes/api');
var app = express();

// Enable Cross Origin Resource Sharing
app.use(function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
    next()
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);

var port = process.env.PORT || '3000';
app.set('port', port);

var server = http.createServer(app);

server.listen(port, function () { return console.log("API running on localhost:" + port); });



Here we are doing the following:

  • Setting up our express and http which will be used to handle requests and send responses back to the client
  • Handling CORS (Cross Origin Resource Sharing), setting the headers allows us to POST to the server from a different domain
  • Setting up the path to out api route and the static path of our API when it is built by the compiler
  • Launching the server on our app object and listening on port 3000

4) Now we will configure our API and routes to handle requests so navigate to api.js in the routes directory and configure with the following:

Set the Dependencies


 var credentials_1 = require("./config/config");
 var express = require('express');
 var router = express.Router();
 var nodemailer = require('nodemailer'); 

Set a route that the email will be POST’d to


router.post('/sendemail', function (req, res) { 

 }); 

Now inside this route we will use nodemailer to create a transport object which will be used to authenticate our email which will be used to send the email:


// create reusable transporter object using the default SMTP transport
    var transporter = nodemailer.createTransport({
        service: 'gmail',
        secureConnection: false,
        port: 587,
        auth: {
            user: YOUREMAIL@GMAIL.COM,
            pass: YOURPASSWORD
        }
    });

Here I am using Gmail (use your gmail account and gmail password).

Create a JSON object which will define the structure of the email:


 // setup email data with unicode symbols
    var mailOptions = {
        from: req.body.name,
        to: 'YOUREMAIL@MAIL.COM',
        subject: 'Query',
        text: req.body.name + '\n' +
            req.body.email + '\n\n' +
            req.body.message
    };

Send our email:


 // send mail with defined transport object
    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            return console.log(error);
        }
        console.log('Message %s sent: %s', info.messageId, info.response);
        res.send(info.responseCode)
    });

Here we are using the sendEmail function that takes in our mailOptions JSON object and sends it then responds with a status code which is then check by the client and a message is displayed saying if it was successful or not.

This is what your api.js file should now look like:


var credentials_1 = require("./config/config");
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');

/* GET api listing. */
router.get('/', function (req, res) {
    res.send('api');
});
router.post('/sendemail', function (req, res) {

    // create reusable transporter object using the default SMTP transport
    var transporter = nodemailer.createTransport({
        service: 'gmail',
        secureConnection: false,
        port: 587,
        auth: {
            user: YOUREMAIL@GMAIL.COM,
            pass: YOURPASSWORD
        }
    });

    // setup email data with unicode symbols
    var mailOptions = {
        from: req.body.name,
        to: 'YOUREMAIL@MAIL.COM',
        subject: 'Query',
        text: req.body.name + '\n' +
            req.body.email + '\n\n' +
            req.body.message
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            return console.log(error);
        }
        console.log('Message %s sent: %s', info.messageId, info.response);
        res.send(info.responseCode)
    });
});
module.exports = router;

Its that simple! To test this just replace the variables in mailOptions to static content.

If you have any problems please leave a comment and I will be glad to help!

Advertisements

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