How to send email using node.js?
nodemailer module is used to send an email in Node.js. First install the nodemailer module from npm.
File Name :
npm install nodemailer
you can include Nodemailer module in any application:
File Name :
var nodemailer = require('nodemailer');
Features of Nodemailer:
File Name :
It supports various features like adding HTML in the mail, Unicode characters, sending attachments with the text, etc.
It uses the simple mail transfer protocol (SMTP).
How to Send an Email
First import this into our application.
var nodemailer = require('nodemailer');
Create Transporter Object: createTransport() method in nodemailer which accepts an object and finally returns a transporter object. This object will be required to send emails.
const transporter = nodemailer.createTransport(transport[, defaults]);
File Name :
const nodemailer = require('nodemailer');
const secure_configuration = require('./secure');
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: secure_configuration.EMAIL_USERNAME,
pass: secure_configuration.PASSWORD,
clientId: secure_configuration.CLIENT_ID,
clientSecret: secure_configuration.CLIENT_SECRET,
refreshToken: secure_configuration.REFRESH_TOKEN
}
});
const mailConfigurations = {
from: 'sana@gmail.com',
to: 'mahira@gmail.com',
subject: 'Sending Email using Node.js',
text: 'Hi! There, You know I am using the NodeJS '
+ 'Code along with NodeMailer to send this email.'
};
transporter.sendMail(mailConfigurations, function(error, info){
if (error) throw Error(error);
console.log('Email Sent Successfully');
console.log(info);
});
Example
File Name :
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email@gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'sana@gmail.com',
to: 'mahira@yahoo.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Multiple Receivers
File Name :
var mailOptions = {
from: 'mahtab.habib@gmail.com',
to: 'sana@yahoo.com, mahira@yahoo.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
html: '
Welcome
That was easy!
'
}
send mail from localhost or without ssl certificate
If you want to send mail from localhost or without ssl certificate, you can execute the following command on your terminal
npm config set strict-ssl false --global
set NODE_TLS_REJECT_UNAUTHORIZED=0
Previous
Next