Send emails from your website to any user super easily!
Tags: javascript, node, nodemailer, emails
Published: 2022-04-18 13:54:02

## Introduction

First of all, let me give you a heads up of what I'm going to be talking about, and the purpose of this blog. In today's world, almost every website or web-app sends all kinds of emails to their respective users, each with a distinct functionality or purpose.

## Purpose of sending such emails

Some examples of those emails are:

- User verification emails (authentication)
- Reset authentication passwords
- Marketing emails
- Subscribing to a newsletter
- Responding to a report case (ticket) 
- Responding to a contact-me form
- Transactional emails

As you can tell, there are a plenty of use cases where it's almost mandatory to send emails to our users right from our platform. But how can we implement an easy way to do so, without so much hassle?

## What is Nodemailer?

[Nodemailer](https://nodemailer.com/about/), by their own definition, is a module for Node.js applications to allow easy as cake email sending. It is the solution most users turn to by default.

## Project Implementation

To start with this quick project, you must have a node.js application pre-set and running already. If you're not very familiar with node.js and need a little help setting up a simple back-end environment, check out my upcoming blog to help you out.

Next up, install Nodemailer in your root directory:

```
npm i nodemailer

```

Now you need to use an email delivery service, which provides you with a simple way to send those quick emails to your clients/visitors. There are plenty of those services available, with each having it's own features and pros over the other. The most common ones are Sendgrid, SendInBlue, HubSpot, omniSend, etc. The one I'll be using is going to be SendIbBlue, due to the ease of their service, and their pretty good customer support, in case of any unexpected issue. Steps for creating an account:

- Visit their official [website](https://www.sendinblue.com/)
- Click on the sign up button on the top right corner
- Go to the SMTP & API tab, [here](https://account.sendinblue.com/advanced/api#tab-account-nodejs-sample)
- Keep this tab open for later on, where we'll be using an API key or SMTP Server necessary for the setup later

## Modifying our node.js app

Now in order to see the magic happen, we need to modify our node.js app. First, Create a file inside the root directory, and call it whatever you like, ex. sendMail.js. Next, import nodemailer as below (P.S. To use import method over require, go to package.json file, and add the option, "type": "module")

```
import nodemailer from 'nodemailer'

```

Then, we'll create and export a function, which contains the following:

1. Creating a transport using nodemailer's createTransport() method, while passing server info, which we got from sendInBlue as an argument

2. Creating a mailOptions object, which contains our email options such as sender email, receiver email, subject of the email, and the email itself 

3. Calling SendMail() method on the transport while passing the above options as an argument

```
import nodemailer from "nodemailer"

//Note that I stored my credentials in my .env file
const { SMTP_KEY, SMTP_PASS, SENDER_EMAIL, REPORT_PASS } = process.env

export const sendReportMail = (to, mailContent) => {
    const smtpTransport = nodemailer.createTransport({
        host: "smtp-relay.sendinblue.com",
        service: "Sendinblue",
        port: 587,
        auth: {
            user: SMTP_KEY,
            pass: SMTP_PASS,
        },
    })

    const mailOptions = {
        from: SENDER_EMAIL,
        to: [to, SENDER_EMAIL],
        subject: "Email subject",
        html: `
            <div >
                    Dear ${mailContent?.name},
                    Thanks for contacting us! We'll make sure to get back in touch as soon as possible!
            </div>
        `,
    }

    smtpTransport.sendMail(mailOptions, (err, info) => {
        if (err) return err
        return info
    })
}

```

Last but not least, we can use this function inside any router controller to easily send user emails, as the example below:

```
export const sendReport = async (req, res) => {
// Getting report data, which the user himself added, while we received this data with a POST request
    const { firstName, lastName, subject, message } = req.body

    try {

            const mailContent = {
                name: `${firstName} ${lastName}`,
                subject,
                message,
            }

            sendReportMail(user?.email, mailContent)

            res.status(200).json({
                message:
                    "Report submitted successfully! Please check your email for confirmation.",
            })
        }
    } catch (err) {
        if (err?.errors?.email?.name === "ValidatorError") {
            res.status(403).json({
                message: "Please enter a valid email",
            })
        } else {
            res.status(500).json({
                message: "Server Error",
            })
        }
    }
}

```

## Final Thoughts

By Implementing the above steps correctly, you could hugely benefit in any of your projects that requires authentication, or if you simply want to send quick marketing emails to your end users. The use cases are definitely much more than that, but in short this would be a great tool to at least try.

I'm constantly writing new blog posts where I share my expertise & skills in topics related to web development. If you're interested in such topics to boost your development career, consider following me! 😇 Or visit my personal [website](https://iamshour.com)!
Thanks for reading, Ciao! 👋