{ Sending Email with Nodemailer. }

Objectives:

By the end of this chapter, you should be able to:

  • Define what a mailer is
  • Use nodemailer to send users emails

mailers

Another very common task when building backend applications is sending email to users. This requires setting up an email server and configuring it with your transactional mail provider (Mandrill, SendGrid, Gmail etc.). To get started sending mail to your users, check out Nodemailer.

A sample application to send emails

Since Gmail is not the easiest to configure and Mandrill and SendGrid do not have a free tier, we will be using mailgun to set up transactional email. You can create a free account here.

Let's now imagine that we want to send some information to a user when a form is submitted. Here is what that configuration might look like:

require('dotenv').load();

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var nodemailer = require('nodemailer');
var mg = require('nodemailer-mailgun-transport');

app.set("view engine", "pug");
app.use(bodyParser.urlencoded({extended:true}));


var auth = {
  auth: {
    api_key: process.env.SECRET_KEY,
    domain: process.env.DOMAIN
  }
}

var nodemailerMailgun = nodemailer.createTransport(mg(auth));

app.get("/", function(req, res, next){
  res.render("index");
});

app.get("/new", function(req, res, next){
  res.render("new");
});

app.post('/', function(req, res, next){
    var mailOpts = {
        from: '[email protected]',
        to: req.body.to,
        subject: req.body.subject,
        text : 'test message form mailgun',
        html : '<b>test message form mailgun</b>'
    };

    nodemailerMailgun.sendMail(mailOpts, function (err, response) {
        if (err) res.send(err);
        else {
          res.send('email sent!');
        }
    });
});

app.listen(3000, function(){
  console.log("Server is listening on port 3000");
});

As an exercise, try to work with this code to create an application that sends email!

Example Application

You can find a small example with Mailgun and Nodemailer here.

When you're ready, move on to Web Scraping with Node.js

Continue