Send email using node.js
In this article, I will explain how to send email using node.js
What is node.js
Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine
Node.js is an open-source server environment. Node.js allows you to run JavaScript on the server.
For more detail please read this doc.
NODEMAILER
We used a third-party plugin called ‘nodemailer’. This plugin helps us to send mail very easily.
For more detail about ‘nodeamiler’ please read this doc.
I will explain using one example. It's not framework dependent. No need to worry about my framework is Fastiy or Express.
Example
Initial setup
$ mkdir sendEmail$ cd sendEamil$ npm init -y
Its generate the package.json file. Then we can install whatever plugin we want.
$ npm install nodemailer
DotEnv
Once the installation is finished then install ‘dotenv’. The ‘dotenv’ for setup for our environment variable for developer purpose.
The main purpose is no need to update your ‘.env’ file on git. Using git ignore method ignore ‘.env’ file.
$ npm install dotenv
Once above all initial setup is finished then move to our code.
Your ‘package.json’ file should be like the above code.
Create server.js, .env and .gitingnore files
$ touch server.js$ touch .env$ touch .gitignore
In your git .gitignore file mention .env. That means you can’t update ‘.env’ file on your git.
.env
Server setup
The above code is the example of creating transport using nodemailer. In your transporter, we should set up the service. The above example I set up service is ‘gmail’. Then we define auth it should have user and pass. We get value from our ‘.env’ file.
Our ‘.env’ the file should be like the above code. But please give valid details.
Send mail
Then moved to send mail part.
The above code is the example of send mail function. We should give valid email for ‘to’ field.
Run your application
We should run your application using the terminal
$ node server.js
If you get an error like ‘email and password not accepted’ because it causes of the security issue so, please open blow link your browser. And enable allow less security app.
https://myaccount.google.com/lesssecureapps.
Once you enable allow less security app then run your application again.
$ node server.js
Check your ‘to’ email address. you will receive email successfully.
Thank you for reading this. Have a great day!
Reference link
Git link:
https://github.com/EdisonDevadoss/node-send-email