Hey, fams! today we are going to learn how to send e-mails, right from our IDE using NodeJS. The module of interest is called Nodemailer.
Prerequisites
๐ NodeJs
๐ Nodemailer
๐ Email account
๐ฏ Steps
Open editor (VSCode ๐), initialize your project with the command below
npminit-y
This command initiates a package.json, package.json.lock, and index.js (main entry file). The index.js will house all our logic.
Dependencies
๐Install Nodemailer
npminodemailer
๐ Import the package inside index.js
constnodemailer=require('nodemailer');
๐จ๐ฝโ๐ซ For security reasons, make sure you install and use dot.env package to prevent your password from being exposed or pushed to GitHub. Install dotenv
npmidotenv-S
Require dotenv in your index.js file. I didn't require it in this project because I am using dummy data.
๐ฏ Next use the mailOption to send your message.
// Email infoconstmailOptions={from:'dsimple@gmail.com',to:'fams@gmail.com',subject:'How to send emails using NodeJS',text:'Follow the instructions and you will be fine'};
๐ฏ Lastly, write:
// Send email ๐ง and retrieve server responsetransporter.sendMail(mailOptions,function(error,info){if (error){console.log(error);}else{console.log('Email sent: '+info.response);}});
When done properly, you should have the following logic in your index.js. That is if you choose not to use the dotenv
To run: type ๐๐ผ in your terminal
nodeindex
Note: On your Gmail, do not forget to accept and allow the "Less secure apps" access to use your scripts with your Gmail SMTP connection. Gmail will alert you with an error if this option is off, you need to turn it on.
constmailOptions={from:'dsimple@gmail.com',to:'fams@gmail.com,myrealfams@gmail.com',cc:'lexus@gmail.com',bcc:'sugar@gmail.com',subject:'How to send emails using NodeJS',text:'Follow the instructions and you will be fine'};
Send attachment
constmailOptions={from:'dsimple@gmail.com',to:'fams@gmail.com,myrealfams@gmail.com',cc:'lexus@gmail.com',bcc:'sugar@gmail.com',subject:'How to send emails using NodeJS',text:'Follow the instructions and you will be fine',attachments:[{filename:"robocop.jpg",path:"./img/robocop.jpg"}]};