How To send emails using Node.js with Nodemailer npm
In this Node.js tutorial, I will tell you how to send email in Node.js using Nodemailer module.
This makes it very easy to send emails from node application.
You can easily installed the Nodemailer module using npm command with Node.js
Nodemailer is licensed under MIT license
.
The best thing is it support unicode, that means you can use any characters including emoji.
You can send raw text as well HTML
content.
You can embed images in HTML, and also can add attachments to messages.
Nodemailer support different transport methods - SMTP, Sendmail and Amazon SES.
In this example, I am sharing simple code to send email in node application using Nodemailer module.
InstallationRun following command to install Nodemailer :
npm install nodemailer --save
Require the Nodemailer module in your js file :
var nodemailer = require('nodemailer');
- function sendMail(to,subject,message)
- {
- var smtpConfig = {
- service: 'Gmail',
- auth: {
- user: 'username@gmail.com',
- pass: 'xxxxxx'
- }
- };
- var transporter = nodemailer.createTransport(smtpConfig);
- var mailOptions = {
- from: '"Sender Name" <sender@gmail.com>', // sender address
- to: to, // list of receivers
- subject: subject, // Subject line
- text: 'Hello world ?', // plaintext body
- html: message // html body
- };
- transporter.sendMail(mailOptions, function(error, info){
- if(error)
- {
- return console.log(error);
- }
- else
- {
- return console.log(info.response);
- }
- });
- }
- var message = '<p>This is HTML content</p>';
- sendMail('ajay.agrahari09@gmail.com','Welcome to ExpertPHP.in',message);