Logo

dev-resources.site

for different kinds of informations.

Send emails from your website to any user super easily!

Published at
4/18/2022
Categories
javascript
node
nodemailer
emails
Author
iamshour
Categories
4 categories in total
javascript
open
node
open
nodemailer
open
emails
open
Author
8 person written this
iamshour
open
Send emails from your website to any user super easily!

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, 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

Enter fullscreen mode Exit fullscreen mode

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
  • Click on the sign up button on the top right corner
  • Go to the SMTP & API tab, here
  • 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'

Enter fullscreen mode Exit fullscreen mode

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
    })
}

Enter fullscreen mode Exit fullscreen mode

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",
            })
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

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!
Thanks for reading, Ciao! 👋

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: