Sending emails in  NodeJs with Nodemailer
Tags: node, smtp, aws, javascript
Published: 2020-06-04 12:45:43

### 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](https://sendgrid.com/blog/what-is-an-smtp-server/) 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](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
```

### 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](www.mailtrap.io) and sign up in a second. On opening, a page in figure below will be seen. 

![Figure 1](https://user-images.githubusercontent.com/23367724/83756364-97c31c00-a68c-11ea-8d71-e1f312f68d8a.png)
*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.

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

```

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

```javascript
//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;
}
```

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](https://user-images.githubusercontent.com/23367724/83756333-8bd75a00-a68c-11ea-87f9-9556b6a16ae4.png)
*Figure 2. Temporary Email address for testing by mailtrap*


```javascript
//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}/`);
});

```

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](https://user-images.githubusercontent.com/23367724/83756683-04d6b180-a68d-11ea-90d3-e1791c9acbd7.png)
*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."