Sending mails over the internet has become one of the most significant features every web application would love to integrate. In this article, we will see how to send email templates using Nodemailer as our transporter service, Handlebars, as our email templating engine.
What We will be building
We will build a simple application where users create an account. When the user registers a welcome email will be sent to the user.
Before we kick off
Learn Vue.js and modern, cutting-edge front-end technologies from core-team members and industry experts with our premium tutorials and video courses on VueSchool.io.
Prerequisites
- Familiarity with HTML, CSS, and Javascript (ES6+).
- Vs code or any code editor installed on your development machine.
- POSTMAN installed on your development machine.
- Basic knowledge of Vuejs.
- Basic Knowledge of Expressjs.
Yea….Lets write some codes …
We will start by setting up the backend for our application. Let’s create a new directory for our application and initialize a new nodejs application. open up your terminal and type the following:
The mkdir
command is used for creating a new directory, while the cd
command is used to move into a directory.
We use the npm init -y to initialize a new nodejs application. This command will create a package.json
file for our application. This is where we will keep track of all our project dependencies.
The code .
command will open up that folder in VS code which is our text editor.
Installing the necessary packages
Now we need to install the necessary dependencies for our backend application. Here are the dependencies we will need for our application:
body-parser
: is a piece of express middleware that reads a form’s input and stores it as a javascript object accessible through req.body.nodemon
: will watch our files for any changes and then restarts the server when any change occurs.express
This will be used to build our nodejs server.cors
: is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.dotenv
: will store all of our environment variables. This is where we will store our email variables.morgan
: This is a package that will log all our application routes.nodemailer-express-handlebars
: This package will help us to set up our email templates.mongoose
: An object modeling tool used to asynchronous query MongoDB.
The first thing we need to do is to install nodemon globally so that it can be accessed anywhere on our local machine. To install that open ur terminal and type this command:
After installing nodemon
globally, we need to install other dependencies for our application:
This command will install all these packages and add them among our dependencies in the package.js
file. It also creates a node-modules
folder which is where all the packages are been stored. Remember not to add this package while you are pushing your project to git. To avoid this we need to create a .gitignore
file. To do this, open your terminal and run this command:
This command will create a .gitignore
file. Open the file and type node_modules
in it.
Creating the Express Server
we need to create our main file, to do that we will create an index.js
file:
We need to create a simple server for our application, this is where our backend application will run:
What we basically did was to bring in some of our project dependencies and configured the packages. What we have to do now is to add a command in our scripts object in our package.json
file to run our backend application:
To run the backend application we can now run npm start
.After running the command we can access our application on localhost:4000
I’m using the JSON view awesome Chrome extension to display my output.
Now that we have our application, we can setup our mongoose models for user registration and contact.
To do that we will create a new directory api for our modules. Note that directory should be created in the server directory, meaning that you have to move into the server directory.
What we are doing here is to basically creating an api
directory and then move into that directory. Inside the directory we create a directories for our User module and inside the directory we created our controller, routes and model files.
What we have to do now is to write a simple script that will configure our mongodb database.in the api
directory, create a config directory and create a db.js
file inside it. This is where we will write our config for our database:
Here we create a mongoose connection to our mongodb server.This will create a new db vue-mailer
. Once the database is connected it will display connected in the console.
Now we need to register this config in our main file(index.js) file:
Note that you have to declare this after you have declared the instance of express.
Let’s start with the User model.let’s create the user schema by adding this into the User/model.js
file:
What we have to do now is to create our mailer config. let’s create a mailer.js
file inside our config directory and setup our nodemailer transporter.
Note if you are using Gmail you have to enable less security. To do this click on this link. This will enable the ability to send mails in 3rd party applications.
Here transporter
is the object that will enable us send mails.The service i will be using is the gmail service. The auth object is where we will add our gmail email and password. For security reasons, we will store this data in our environment variable.To do this, create a .env file and add the following:
Replace youremail
and yourpassword
with your email and password respectively. And DON’T forget to add .env
to the .gitignore
file to prevent commiting it on git.
Next up we need to configure express handlebars for templating.
Let’s start by creating a views directory, after doing that create 3 more directories inside of it which are layouts
,partials
and templates
:
Inside the layout directory, create a main.handlebars
file and add the following code:
This will be the default wrapper for our template meaning that all templates will be mounted here. We won’t be adding any file in our partials directory for now.
All our email templates will be defined in the templates directory.
Next up lets configure express handlebars to use this directory for templating:
Here we define our extension name. The fun part about handlebars is you could actually change you extension name to anything of your choice.
The viewEngine
object is basically a config pointing to the directories that we created.
With this now we can start creating our Email templates.This email templates will be basic HTML.
Its a good practice to write your email templates in HTML tables for good responsiveness.
ets head over to the template directory and create a new welcome.handlebars file and add the following codes:
This is a basic HTML template, We will dynamically pass in the users name into the template using {{user}},and also pass in the users email we will be sending the mail to.This data is gotten from our transporters context.
We now need to create a function that will send the mail once a user registers.To do that lets add this to our mailer.js
file:
Now that we have our welcome email template, lets implement the registration controller.we will make sure that the registration was successful before the mail is been sent.
let add this code to our User/controller.js
file:
Let me explain what is happening here.
- We start by bringing in our user model and our mailer module.
- We create a function
registerNewUser
and create a new instance of User; - We use the
save()
method to save the inputted data into our MongoDB - Now if the save method was successful, we call the
mailer.welcomeMail
method and pass the user’s name as a parameter. - After that, we send a response if it’s successful, but if it isn’t the catch block will throw the error.
Next up we need to create our route that will handle this controller function.To do that, lets add this to our User/routes.js
file:
What will likely do now is to register our root routes.This is a good approach for handling routes in Expressjs. To do that add this to your api/routeHandler.js
file:
Now we need to register our routeHandler.js
file in our index.js
file:
Testing Our Backend
Now that we have completed our backend, Lets test the endpoint using Postman.
Remember to set the data type to JSON, and also set the request type to POST.
After doing this, send the request and open up your email application.You will get a mail like this:
Thats basically the functionality of our backend. Next up we need to create our Vuejs application.
Setting up the Front-End
We will use Vue inline for this application as it is very simple.Lets create a client folder, this is where we will be setting up our frontend application:
What we basically did here was to create a Client folder and the move into that folder.We went ahead to create an index.html
file and an index.js
.The index.js
file is where we will be writing all our vuejs codes.
Lets setup a simple HTML boilerplate and the link our index.js
file to it. We will also be using axios
to make our request so we will add the axios
CDN into our html file.
All of our Vuejs code will be written inside the div with the id of app
.
We will use live-server to run our frontend application. If you don’t have live-server
installed on your local machine then open up your terminal and run:
npm i live-server -g
After installing it you can run your front end application by running :
This will open up our application on port 4040
.
You will have this on your browser:
Now that we have our frontend running, we need to create our registration form. We added the bootstrap CDN, so we will be using bootstrap for our UI. lets modify our div with the id of app with this:
Next up we need to setup our vue application by setting up our state for the form and also write a method to register the users. Lets modify our index.js
file to this:
We now need to bind our data to the input fields.To do that lets modify our form:
Note that we add a conditional to the spinner so that it initialises when we try to register:
Conclusion
You could add better features to your application by adding a contact section Where users can send mails to the admin. This would help understand Nodemailer better. For source code, click here.