Sending Emails using NodeJs. How to send Email with nodeJS. In this tutorial, We will learn how to send emails in NodeJs using nodemailer library.
- Install the nodemailer library
D:\work\Codebun\Email>npm i nodemailer
- Create app.js file and require nodemailer
Var nodemailer = require(“nodemailer);
- Create a variable to give the sender’s details like email service, email id, and password using a nodemailer function createTransport(). And pass the parameter.
Var transporter = nodemailer.createTransport(_paramenters_)
- Create a variable to pass the data of the receiver such as email address(one or more), subject of the mail, text content, and HTML content. Pass the information in JSON format. And Also pass the senders email option created in the above variable.
- Uses the sendmail function and passes the receiver’s data as the parameter in the function and gives a callback hit.
- The callback function consists of two-parameter error and info-sended.
var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'abcde@gmail.com', pass: 'xxxx' } }); var mailOptions = { from: 'abcde@gmail.com', to: 'codebun@gmail.com, xyzabd@gmail.com', subject: 'Sending Email using Node.js', text: `Hello sir this email is sent You through the node js system and work awsomely.` // html: '<h1>Hi USer</h1><p>Your Messsage</p>' }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } });
Note:
- When passing Email and password please use the environment variables option for maintaining privacy.
- Allow access from your mail setting to send email using servers.