EMAIL NOTIFICATION USING NODE.JS

Chime Princewill
FAUN — Developer Community 🐾
8 min readJun 29, 2020

--

Photo by Davide Baraldi on Unsplash

Have you ever wanted to send an email to a user after signing up for your web/mobile application or after a certain change in the user operation?

This article will make life easier and put u straight in the steps to achieve that.

Prerequisite:

Before starting, you should have a basic knowledge of JavaScript, nodejs, and have it installed in your system.

In this article, I will be using vs code editor, but you may use any of your preferred code editors.

Let us head to our editor and open a new folder for our application

If you are using vs code, hit ctrl K + O or hit the file > open new folder button to create a new folder or open the terminal by pressing ctrl + ` in vs code and follow the following steps.

cd Desktop
mkdir email-application

If u have done that, let us create a new file, named index.js.

cd email-applaication
touch index.js.

If we look at the file paths in our vs code we should see the index.js file created.

Going further, let us install the node packages we will be using in the application. On the terminal, run the following:

npm init -y
npm install nodemailer cron-node --save

Above we did a no-frills initialization of the node project, installed the node mailer — a package for sending emails.

The cron-node is a timing package that will help us to send an email to the user at a specified time — just like what setInterval method does.

The save flag after the package names is to have the installed packages saved to our package.json file as we can see in the following:

the package.js file created with npm init -y

Looking closely, you will notice that the scripts object got us with a test key and a value that throws an error message. In our case, there is no test file specified. Let us go back to the package.json file and replace the test inside the scripts object with the following:

"start": "node index.js",
hit Crtl + s to save

Now we can run our node project by running node <file path>

node index.js or npm run start

Go to the index.js that we have created, and require those packages that we installed for consumption.

declaring our variables

Setting mailing in nodeMailer:

NodeMailer provides us with a test account API that we can use to generate an account on the ethereal email page. It enables us to test our application with a fake message that will not be sent to a real mailing account.

creating a fake account

The createTestAccount function was called, it possesses two arguments, the error, and account.

An error message is returned if the creation of the email account with ethereal wasn’t successful, while the account holds the user-generated credentials.

Let us run the following command in the terminal to print the account information:

node index.js
the user account information

Let us create a transporter that will transport the message to the ethereal site for previews.

This brings us to another function of the nodeMailer called createTransport. In the index.js file add the following:

created transporter object

The screenshot shows a nested function that returns the transporter object.

The createTransporter is a parent function that passes a parameter called userEtherealData to its child function(createTransport). The child function is a method in nodeMailer for creating a transporter(medium/criteria).

Probably, the following questions should be in our mind:

  • Where are we calling the function?
  • why the parameter?
  • Why nest the nodeMailer function since it’s a function?

Alright, all will be clear in no time I promise.

First question

The function is returned in the createTestAccount function to have power to the ethereal account like so:

your createTestAccount should look this way

Second question

About the parameter, the parameter is also assigned a value in the function above with the generated mailer information(account) that was passed to the child function argument.

Third question

The function was nested to separate the function from createTestAccount function above; to have power to the user account information in the createTestAccount function, and to have a neat and concise code structure.

Moving further, let us now call on another powerful method of the transporter called the SendMail method. This method serves as a medium that will be sending the mail to the specified user.

It has some arguments which are passed in its method, it holds two main arguments,

  • Mail options and
  • A callback function

The callback function returns an error and message information in its
callback.

Firstly, let us declare the mail option separately for a concise code structure. Add the following in the index.js file.

the function that sends the message to the user

A structureMailOption was created, it holds a mailOption object in it.

The mailOption has the criteria to which the transporter.SendMail function needs to perform its operation.

The else condition logged the message identifier and a method(getTestMessageUrl) that logged the preview URL of the mail that was sent. The following is the logged result;

the success message from the transporter

The screenshot is a successful response from the transporter.

  • The first line is the response that notifies us that the ethereal account was generated successfully.
  • The second message there is the message identifier.
  • The third is the preview URL that links us to the ethereal email page to see our test-out message preview.

the following is the preview page from the ethereal email.

preview message

Wow! we have successfully learned how to use node mailer to send an email to your client with a test-out account from ethereal email.

Let us know how we can send a real message with your Gmail account to a client mailing account.

Sending email with a real account

The nodeMailer.createTestAccount function will not be necessary any longer. We will be using a real mailing account to send the email to the users/client.

In the package.json file, inside the scripts object add a new property that will enable us to run the new file we will create in our working directory afterward. Your scripts object should look like the following:

the package.json file

Let us add a new file to our working directory name send_mail_with_real_account.js. Run the following command in your terminal:

touch send_mail_with_real_account.js

Inside it, require the node mailer and node-cron. Go to the index file, copy the structureMailOption function, paste it into the new file we created and make some adjustments as follows.

the send_mail_with_real_account.js file

We require the nodeMailer and node-cron dependency that is needed. We adjusted the mailOption object, the “from and to” property with a real sender and receiver credential. The getTestMessageUrl in the else condition will return false this time because we have required a real account to use and not a generated one from the ethereal email.

Again, we will copy the createTransporter function in the index.js file to the new file we created above.

adjusted the createTransporter function

Here, we added the service property that holds the mailing service we want to use and the auth object that holds the sender’s real email account.

If you noticed, no argument was passed to the createTransporter function unlike in the index.js file. Lastly, the structureMailOption was called in the createTransporter function.

There is one challenge that may likely occur. Meanwhile, add up the needed credential in the appropriate field and try to run the following:

npm run devNote: That you must be connected to an internet or wifi

Any errors? believe yes! Now let’s know what the error will be;

Firstly, we will receive an “invalid login” error like so in our terminal;

error from our local message

Secondly, Google will send you a “critical security alert” that look like so:

a security alert from google

Believe me, your code is perfectly in order. The message was due to a change we didn’t make in our Google account, to allow access to your Google account, follow the following steps.

steps to achieve that

  • Go to your Gmail/Google account
  • Click on your Google profile image at the top right of your Gmail/Google page
your google image
  • Click on the manage account button
  • Click on the sidebar security button
  • scroll to the following view:
the less secure app access
  • Allow access by clicking the “Turn on access (not recommended)

Let us reload our node application again.

Note: with a real account to your client mailing account
my Gmail message inbox

Wow! This is awesome!! It seems like magic right?

The power behind the node is more than we can imagine. Now you can successfully update your client/user of their sign-up credentials and changes in their account with ease.

I believe you would want to know how to send mail to multiple users. Is simple, in the structureMailOption adjust the “to” property like so:

to: `princewillchime43@gmail.com, another user account`

Enclose the user's Gmail account in back-tilt and separate with a comma(,).

Let us use our node-cron installed to automatically set the message to the user at a specified interval of time. The following lies the secret to that.

sending an email every minute

Finally, we have successfully sent an email to the user every minute. Notice that the createTransporter function is now returned inside the schedule method of the cronjob. For the full source code access me

I believe that this article is of great help to us and we learned a lot as well.

Follow me in medium to see a more interesting article written by me and my Linkedin

Join FAUN: Website 💻|Podcast 🎙️|Twitter 🐦|Facebook 👥|Instagram 📷|Facebook Group 🗣️|Linkedin Group 💬| Slack 📱|Cloud Native News 📰|More.

If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇

--

--

I am a very passionate web developer {MERN STACK}, currently working with Descasio as a Full Stack Engineer. I am open to new roles (Remote)