how to send email in nodejs using nodemailer NPM module.
In the code snippets that follow, we will go through each of the above steps.
STEP 1: Install the nodemailer package.
npm install nodemailer
Once you are done with this article, you should probably learn more about nodemailer library from here.
.
STEP 2: Creating a transport object in your route handler.
var nodemailer = require('nodemailer');
var router = express.Router();
app.use('/sayHello', router);
router.post('/', handleSayHello); // handle the route at example.com/sayhi
function handleSayHello(req, res) {
// Not the movie transporter!
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'example@gmail.com', // Your email id
pass: 'password' // Your password
}
});
...
...
...
}
STEP 3: Prepare some plaintext or HTML content to be sent in the body. I am going to simply use some text.
var text = 'Hello world from \n\n' + req.body.name;
STEP 4: Create a simple JSON object with the necessary values for sending the email.
var mailOptions = {
from: 'example@gmail.com>', // sender address
to: 'receiver@destination.com', // list of receivers
subject: 'Email Example', // Subject line
text: text //, // plaintext body
// html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead
};
STEP 5: Your moment of glory! — Actually send the email and handle the response.
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
res.json({yo: 'error'});
}else{
console.log('Message sent: ' + info.response);
res.json({yo: info.response});
};
});
And thats pretty much all there is to it! It was quite simple, wasn’nt it?
No comments: