Node.js Send an Email

Spread the love

The Nodemailer Module

The Nodemailer module makes it easy to send emails from your computer.

The Nodemailer module can be  installed using npm command see example.

C:\Users\pc\Desktop\nodeJsTest>npm install nodemailer

4 3

var nodemailer = require(‘nodemailer’);

Send an Email

Now you are ready to send emails from your server.

Use the username and password from your selected email provider to send an email.
I will show you how to use your Gmail account to send an email.

——————————————————————————

var http=require(‘http’);
var nodemailer=require(‘nodemailer’);

var transporter = nodemailer.createTransport({
service: ‘gmail’,
auth: {
user: ‘[email protected]’,// you need replace your one
pass: ‘jqwaswcextlopkig’//you need replace your one
}
});

var mailOptions = {
from: ‘[email protected]’,
to: ‘[email protected]’,
subject: ‘Sending Email using Node.js’,
text: ‘That was easy!’
};

http.createServer(
function (req,res){

transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log(‘Email sent: ‘ + info.response);
}
});
res.end();
}

).listen(8080);

 


 

5 2

And that’s it! Now your server is able to send emails.

 

Multiple Receivers

Send email to more than one address:

var mailOptions = {
from: ‘[email protected]’,
to: ‘[email protected],[email protected]’,
subject: ‘Sending Email using Node.js’,
text: ‘That was easy!’
};

You can change above line as needs.

 

6 3