Hey guys,
Today I want to show you how to use nodemailer in node.js to send email.
Node.js has a very active community that are adding new modules daily to the npm (node package module or node package manager), one my favorite module in node.js is nodemailer, this module helps you to send email to any recipient that you want, these are the steps that you need to take in order to use this module.
- You must install nodemailer as it is not a core module in node.js
Npm install nodemailer
- Create a object from the module.
const nodemailer = require('nodemailer');
- Create function that sends email and code all the configurations in this function:
</pre> <pre>function sendEmail() { // you need to create an object that contains all the sender email configuration var transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'your@email.com', pass: ' you password ' } }); // You need to create an email content var mailOptions = { from: 'janfeshan.mehran@gmail.com', to: 'info@codingtips.net', subject: 'Your order is ready', text: 'Your order is ready for delivery', html: 'Your order is ready for delivery' }; //Pass the email content to transporter in order to send email. transporter.sendMail(mailOptions, function (error, info) { if (error) { console.log(error); res.redirect('/'); } else { console.log('Message Sent: ' + info.response); res.redirect('/'); } }); }</pre> <pre>