DEV Community

vaibhav aggarwal
vaibhav aggarwal

Posted on • Edited on

Sending emails in NodeJs with Nodemailer

Introduction

While making a product communication with the customers is one of the most important factor. The formal and continuous communication for the upcoming events, newsletter and other cyclic events happen through email servers. There are events when email needs to be sent based on specific action performed by the customer.

Consider the mentioned specific actions by the user:

  1. Register for the product
  2. Buys or avails any service
  3. Updates about transactions
  4. Query related to the product

Hence, emails needs to be sent triggered through some APIs. A email server needs to contacted and carry out the communication. An SMTP (Simple Mail Transfer Protocol) server is an application that’s primary purpose is to send, receive, and/or relay outgoing mail between email senders and receivers. Read more about SMTP server.

After setting up a server (article for another day) a transported is needed to send emails through that.

Nodemailer is zero dependency module for Node.js applications that allows sending email in an easy manner. Its flexible and supports SMTP and other transport mechanism. It can be configured for aws-ses, sendgrid and other smtp providers. Read more about nodemailer at nodemailer.com

Some of the features of nodemailer:

  • Zero dependecny on other modules
  • Secure email delivery with TLS and DKIM email authentication
  • HTML content and embedded image attachments

Lets integrate nodemailer in our project and start sending some emails.

  npm install nodemailer 

  // If to include in package.json
  npm install --save nodemailer
Enter fullscreen mode Exit fullscreen mode

Create a transporter

SMTP protocol is the most common transporter for sending mails. It makes integration very simple. Set host, port, authentication details and method.

SMTP can be setup on various services such as aws-ses, gmail etc. But here as our main focus is on to use nodemailer, lets use mailtrap. Mailtrap integrated as a SMTP server and enables you to debug emails in a pre-production environment.

Go to mailtrap.io and sign up in a second. On opening, a page in figure below will be seen.

Figure 1
Figure 1. Mailtrap account to setup and use as an pre production SMTP server

Now, we have SMTP credentials, lets setup our transporter for nodemailer.

//server.js
var transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "2a591f5397e74b",
    pass: "c8115f6368ceb0"
  }
});

Enter fullscreen mode Exit fullscreen mode

Nodemailer uses transporter to facilitate sending mails. Next steps will be setting up email configurations.

//server.js
/**
 * Sends mail through aws-ses client
 * @param options Contains emails recipient, subject and text
 */
const send = async options => {
  const message = {
    from: `${options.fromName} <${options.fromEmail}>`,
    to: ${options.userEmail},
    subject: ${options.subject},
    text: ${options.message}
  };

  const info = await transporter.sendMail(message);
  console.log(info.messageId);
  return info;
}
Enter fullscreen mode Exit fullscreen mode

One thing to notice is that, here in message object text field will have normal text. But the emails, you generally receive are beautiful and formatted rather than just plain text. As mentioned above, nodemailer provides options to send HTML and image attachments.(I will write another article covering all features of nodemailer and how to send beautiful HTML based emails)

In the to section, take email from mailtrap.io. It provides temporary email addresses for testing.

Figure 2
Figure 2. Temporary Email address for testing by mailtrap

//server.js
const http = require('http');
const express = require('express');
const nodemailer = require('nodemailer');
const app = express.Router();
const port = 3000;

app.post('/email', async (req, res) => { 
  try{
   const response = await send(req);
   console.log(response);
   res.status(200).json({
    message: 'sucess',
    data: response
   })
  } catch (error) {
   console.log(error);
   res.status(400).json({
    message: error.message
   })
  }
})

var transporter = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "2a591f5397e74b",
    pass: "c8115f6368ceb0"
  }
});

/*
Use in your req.body
 const options = {
   userEmail: <mailtrapEmail>,
   subject: 'Welcome to Auffr',
   message: 'We are excited to have you in the family'
 }
*/
/**
 * Sends mail through aws-ses client
 * @param options Contains emails recipient, subject and text
 */
const send = async options => {
  const message = {
    from: `${options.fromName} <${options.fromEmail}>`,
    to: ${options.userEmail},
    subject: ${options.subject},
    text: ${options.message}
  };

  const info = await transporter.sendMail(message);
  console.log(info.messageId);
  return info;
}

const server = http.createServer((req, res) => {
  res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('This is the Main App!\n');
});

server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Enter fullscreen mode Exit fullscreen mode

On running the file server.js, express server will be up and running at http://localhost:3000/ . As mentioned above, a post request made at the endpoint /email will send an email to the mailtrap account.

I used postman to make a simple post request at endpoint http://localhost:3000/email. Voila, email is received and visible in our mailtrap account inbox.

Figure 3
Figure 3. Email received through /email endpoint

In next article, I will share how nodemailer can achieve so much more than discusses here.

"I am not an expert, please comment and correct me if I am wrong anywhere. Always love to have a discussion."

Top comments (5)

Collapse
 
ziizium profile image
Habdul Hazeez

You can provide a language after the three back ticks before the code blocks and your JavaScript code will be rendered with syntax highlighting.

The following is taken from your code snippet:

//server.js
const http = require('http');
const express = require('express');
const nodemailer = require('nodemailer');
const app = express.Router();
const port = 3000;

// remaining code
Collapse
 
alakazam03 profile image
vaibhav aggarwal

Hey, Habdul Hazeez. Thanks for the great tip man.

I have made the changes and it sure does look a lot better. Appreciate it.

Collapse
 
lucanerlich profile image
Luca Nerlich

Thanks for the tutorial. Id love if you would enhance it with some kind of spam protection measures :)

Collapse
 
alakazam03 profile image
vaibhav aggarwal

Hi Luca. Thanks for reading the article. Sure, I will cover spam protection, automated response and some other cool things in the next article.

Collapse
 
steve-lebleu profile image
Steve Lebleu

Thanks for the sharing. There is cliam if you want to send email in node.js in a flexible way: github.com/steve-lebleu/cliam