Logo

dev-resources.site

for different kinds of informations.

Sending Emails from a Nodejs Application using Nodemailer

Published at
3/15/2023
Categories
email
node
nodemailer
javascript
Author
tonieng
Categories
4 categories in total
email
open
node
open
nodemailer
open
javascript
open
Author
7 person written this
tonieng
open
Sending Emails from a Nodejs Application using Nodemailer

As a Software Developer, you've probably worked on a project where you need to communicate some information in real-time from your Nodejs application.

This information can be anything from password reset to notifications on subscription services, to changes in terms and services. There's a whole lot of information that can be communicated and there are several ways through which we can send this information.

In this article, we will learn how to send emails from a Nodejs application using nodemailer.

Why use Nodemailer?

There are different reasons why we should use Nodemailer to send emails, I've listed some of them below:

  • We can send different types of data like plain text, HTML content, etc.

  • It has OAuth2 authentication.

  • It has Unicode support for any character, which means we can send emojis within our emails

  • It uses different transport methods like the SES transport method in addition to the built-in SMTP support.

Prerequisites

To follow along, you would need the following:

  • A code editor of your choice (preferably VS Code) and a stable internet connection.

  • An updated version of the Nodejs software is installed on your local device. You can visit the Nodejs download site and follow the prompts to install it.

  • Minimal experience working with nodejs applications using express.js

  • Experience using API testing tools (preferably postman)

Now let's get to coding.....

Initializing our Nodejs project

  1. Create a new folder, with any name of your choice and open it with your code editor. In this case, we used VS Code and we have named our folder "nodemailer-tutorial".

  2. Open up your terminal and type in the following command

  3. Now we need to install the dependencies that will be needed for this project. On your terminal, type in the following command and press enter.

  4. Now we're done with the installation, go into the package.json file and within the script object, add this line of code.

  5. For the next step, we need to create files and folders for our application.

Configuring our App and Creating Routes

Navigate to your index.js file and write the lines of code below:

const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const app = express();
const email = require("./routes/email");

app.use(express.json());
app.use(
  cors({
    origin: "*",
  })
);
dotenv.config();

app.get("/", (req, res) => {
  res.status(200).send("Welcome");
});

app.use("/email", email);

app.listen(process.env.PORT || 3000, () => {
  console.log(`Server is up and running`);
});

Enter fullscreen mode Exit fullscreen mode

Here, we are importing the modules and packages we imported earlier and then configuring them. Also, we set up our app to listen on port 3000. To start up our application, open your terminal, type in npm start and hit enter. You should see a message that reads "Server is up and running". Go to postman and send a get request to this URL http://127.0.0.1:3000/. You should be met with a "Welcome" message like the one below.

Now go into the email.js file and then type in the following lines of code

const router = require("express").Router();
const sendMail = require("../utilities/sendemail");

router.post("/", async (req, res) => {
  try {
    // Here is where we write our logic and functionalities to send the email
  } catch (error) {
    res.status(500).send(error.message);
  }
});

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

Here we just set up the route that will be used for sending our emails. We also imported a module in the second line which is a function that defines how our emails are sent and structured.

Before we write out this function, we need to enable some security features on our host account (the email address from which we would send out emails). Go to your account settings and set up an "Application specific" credential for your nodejs application and you'll be provided with a password. Open up the .env file and type the following code.

HOST = smtp.gmail.com
SERVICE = gmail
EMAIL_PORT = 587
SECURE= true
USER = [email protected] //Replace with your email address
PASS = password // Replace with your application-specific password

Enter fullscreen mode Exit fullscreen mode

Note *: We are using Gmail in this tutorial. The settings might be different if you use another email service.*

Now go over to the sendemail.js file and type in the following code

const nodemailer = require("nodemailer");

module.exports = async (email, subject, text) => {
  try {
    // initialize and define the mode of transport
    const transporter = nodemailer.createTransport({
      host: process.env.HOST,
      service: process.env.SERVICE,
      port: Number(process.env.EMAIL_PORT),
      secure: Boolean(process.env.SECURE),
      auth: {
        user: process.env.USER,
        pass: process.env.PASS,
      },
    });

    // Defining the mail and sending it using the transport
    const sentEmail = await transporter.sendMail({
      from: process.env.USER,
      to: email,
      subject: subject,
      text: text,
    });
    const response = "Email sent successfully";
    console.log(response);
  } catch (error) {
    console.log(error.message);
    return response;
  }
};

Enter fullscreen mode Exit fullscreen mode

Here, we created a function and within it, we used the nodemailer package to create a transport. Transport defines the method and medium that will be used to send the email. We also called the sendMail method that sends the email using the preselected transport object.

You can access the nodemailer documentation to learn more about these methods and parameters.

Back to the email.js Route

We can now use the sendemail function. To do that, update the code to look like this

const router = require("express").Router();
const sendMail = require("../utilities/sendemail");

router.post("/", async (req, res) => {
  try {
    const email = await req.body.email;
    const message = await req.body.message;
    const subject = await req.body.subject;

    const sentEmail = await sendMail(email, subject, message);

    return res.status(200).send("You email is on the way");
  } catch (error) {
    res.status(500).send(error.message);
  }
});

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

Let's test this out on postman. Copy the JSON object below and provide the details you want to send:

{
    "email": "[email protected]", //Input the address you want to mail
    "subject": "Testing my email server", //Change to any subject you want
    "message": "Confirm you can see this" //Use a personalized message of your choice
}

Enter fullscreen mode Exit fullscreen mode

Back to postman, go to "Body", click on "raw" and then select JSON. Paste the JSON object into the text area and send a post request to http://127.0.0.1:3000/email. Your request should look like this

Now check your recipient email inbox and you will see your message sitting right there waiting to be clicked.

Conclusion

And that's a wrap. We've successfully built a Nodejs application that enables us to send emails using Nodemailer: a module that allows you to send emails from your server with ease.

I've provided a link to the project on GitHub. Here you can find all the code snippets used for this project.

If you have any questions or suggestions, I'll be buzzing to hear from you in the comment section.

Happy coding 💫

nodemailer Article's
30 articles in total
Favicon
Brevo smtp emails to other gmail accounts silently failing , verified domain to the rescue
Favicon
Send emails using Nodemailer (Typescript)
Favicon
Simple Emails Sending from Node.js Using Nodemailer and SMTP
Favicon
Practical Guide to Send Emails from NodeJS/Express App using Gmail and Nodemailer (Screenshots and Code)
Favicon
Sending Emails in NextJs via Nodemailer
Favicon
Sending Emails in Node.js Using Nodemailer
Favicon
Sending e-mails with Sendgrid
Favicon
NestJS Emails with react-email and nodemailer
Favicon
nodeMailer after google security update
Favicon
Beginner’s Guide On Sending Automated Emails With Node.js, Nodemailer, and Cron Jobs
Favicon
Tracking Email Activity from AWS Simple Email Service (SES)
Favicon
Envio de email com NodeJS e Gmail
Favicon
Setting up Node.js Email Server with Nodemailer and Mailtrap
Favicon
Sending Emails from a Nodejs Application using Nodemailer
Favicon
Dynamic emails with handlebars and nodemailer
Favicon
Sending e-mails with Mailtrap
Favicon
Simple Next.JS Form to Email Using React-Hook-Form and Gmail
Favicon
How to send Email with NodeJS in 2022
Favicon
How to send email attachments using nodemailer
Favicon
Send emails from your website to any user super easily!
Favicon
How to Send an Email with Nodemailer
Favicon
Send email using next.js, react-hook-form, tailwindcss & nodemailer
Favicon
Nextjs - Nodemailer - React Hook Form - Tailwindcss
Favicon
How to send mail using Nodemailer?
Favicon
I created my own email server to send emails into my gmail for My Portfolio
Favicon
How to send mail using nodemailer in Angular 11?
Favicon
How I met your...Scraper?
Favicon
Отправка писем в NestJS используя nodemailer. Публикация скриптов.
Favicon
3 ways to send emails with only few lines of code and Gmail - Javascript - Part 1
Favicon
NodeJS – Send email by Nodemailer

Featured ones: