Skip to main content Skip to docs navigation
View on GitHub

NodeMailer: Send Email from Nodejs Application

Advertisments

Suraj Vishwakarma 02-02-2021

Send Emails are becoming important in every application. So, In this article, we will see how we can send Emails in the nodejs applications. I will be using a package called “Nodemailer” to send emails. To test the application we will be using “mailtrap” which is a free service to test.

Note:

You cant add a nodemailer package to the frontend. It is a node package.

Prerequisites:

  1. Nodejs installed
  2. local running server.

You can check out the articles here for the above prerequisites:

https://mdpuneethreddy.com/expressjs-how-to-start-with-nodejs-and-express

Objectives:

  1. Install Nodemailer
  2. Add Post request in backend
  3. mailtrap.io to test the endpoint
  4. Send Email

Install Nodemailer:

You can add the Nodemailer package using yarn or npm. I will be using yarn

yarn add nodemailer

Add Post request in the backend :

We will create an endpoint to send the email. Here I will be creating a post request to send the email.

app.post("/api/sendMail",(req,res)=>{
})

Send Email:

  1. Import nodemailer into the file
import * as nodemailer from "nodemailer"

2. Further we can use Gmail to capture the traffic or we can use a testing site to capture the traffic. I would personally recommend having a testing site than your Gmail.

In this article, I will be using “mailtrap” to capture the traffic.

3. Below are the steps to create an account in mailtrap.

  1. visit link https://mailtrap.io/
  2. Next signup and login
  3. Select nodemailer in integartions, you can see something like below. In integrations, choose Nodemailer.
import * as nodemailer from "nodemailer"
------
var transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "username"
    pass: "password"
  }
});
------
app.post("/api/sendMail",(req,res)=>{
})

Final Code

import * as nodemailer from "nodemailer"
const transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "username"
    pass: "password"
  }
});
app.post("/api/sendMail",(req,res)=>{
const mailOptions = {
        from: you@gmail.com// host address
        to: client@gamil.com, 
        subject: "test Email", 
        html: "Testing Mail" 
      };
      
transporter.sendMail(mailOptions,  (err, info)=> {
        if(err)
          res.status(400).send({error:"failed to send"})
        else
          res.send({message:"Successfully sent"})
     });
})

 

Comments