SlideShare a Scribd company logo
1 of 23
Download to read offline
NodeMailer Example:
How to Send Email
using NodeMailer
with Gmail & Mailtrap
www.bacancytechnology.com
Ways of communication have evolved
over the years. And sending email is
considered the most professional and
widely used feature in the web area.
Emails are used for interacting and
communicating with your customers so
that they don’t miss any important
updates.
Introduction
Most of all, the applications use email as their
feature for communicating with the users. Have
you ever thought about how applications send
emails? If you are looking for an answer for
your ‘how,’ then you’re at the right place!
In this tutorial, we will learn how to send emails
from the Node.JS app with the help of
NodeMailer. With the help of the NodeMailer
example, we will cover sending emails with
basic HTML content and attachments.
For setting up the fake SMTP server, we can use
Mailtrap or Gmail accounts. In this blog, we will
learn how to send email using NodeMailer with
both- Mailtrap and Gmail accounts; you can
prefer whichever you want to.
What is
NodeMailer?
Zero dependencies on other modules
Secure emails delivery
HTML content or embedded attachments
Unicode support
Various transport options besides SMTP
NodeMailer is the most famous module used for
sending and receiving emails from NodeJS
applications. It is a zero dependency module for
your NodeJS apps.
You can easily send emails as plain text, HTML,
or attachments (image, document, etc.).
Here are some of the features of NodeMailer
that makes it best and popular-
Let’s start with our NodeMailer example and
learn how to send email using NodeMailer.
NodeMailer
Example: How
to Send Email
using
NodeMailer
There are innumerable modules and packages
available for sending emails. From them,
NodeMailer is said to be the most favorable and
famous that allows you to send emails hassle-
free.
Follow this step-by-step guide for developing a
demo application and implement NodeMailer in
your NodeJS application.
Step 1: Getting Started
Create a new directory and run the npm init
command for generating the package.json file.
Use these below commands:
$ mkdir nodejs-email
$ cd nodemailer
$ npm init -y
Step-2: Install dependencies
Install the NodeMailer module using npm:
$ npm install nodemailer
Install the dotenv package to store user
credentials.
$ npm install dotenv
Create a file named .env having two variables:
EMAIL_USERNAME– For account ID
EMAIL_PASSWORD– For password
Create an app.js file in the directory for the
NodeMailer end-point. To keep it simple, we
will write the complete code in app.js.
You require the below syntax for loading
packages:
require('dotenv').config();
const nodemailer = require('nodemailer');
Step-3: Using SMTP for
Nodemailer Transport
SMTP (Simple Mail Transfer Protocol) is used to
send emails between various servers. Almost all
the email systems are SMTP-based for sending
emails over the Internet.
let transport =
nodemailer.createTransport(options[, defaults])
options – It is an object that is used to connect
with any host.
defaults – It is an object combining into each
message object. With its help, you can define
shared options, e.g., setting the default address
for email.
Nonetheless, for sending a message via our
transport, configuring the connection must.
Moving forward in our NodeMailer example.
Create a brand new Mailtrap account
Create new inbox
Get your credentials
Step:4 Connection with
Mailtrap Account
We can use Mailtrap- a dummy SMTP server.
Rather than testing the demo with your mail
and piling the inbox with test and unwanted
emails, use Mailtrap as an end-point.
If you don’t have a Mailtrap account, follow
these steps-
Later use the credentials into nodemailer’s
transport object.
let transport = nodemailer.createTransport({
host: 'smtp.mailtrap.io',
port: 2525,
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD
}
});
Keep your username and password inside the
.env file and use it here.
Step:5 Connection with Gmail
Account
In case you want to use your Gmail account use
the below code snippet. Keep the credentials
into the transport object.
let transport = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD
}
});
port – if secure is false, it uses 587, by default,
and 465 if true
host – it’s an IP address/hostname for
connecting to (by default to ‘localhost’)
auth – it defines authentication data
We have discussed both connections over here-
Mailtrap and Gmail. You can use any one
transport connection at a time for sending an
email.
Step: 6 Sending an Email with
Text
const mailOptions = {
from: 'sender@gmail.com', // Sender address
to: 'receiver@gmail.com', // List of recipients
subject: 'Node Mailer', // Subject line
text: 'Hello People!, Welcome to Bacancy!', //
Plain text body
};
transport.sendMail(mailOptions, function(err,
info) {
if (err) {
console.log(err)
} else {
console.log(info);
}
});
Note: Before sending an email from your Gmail
account, allow non-secure apps for accessing
your Gmail account. For that,
Go to your Gmail account settings.
Enable less secure apps for sending emails
from NodeMailer.
These are fields of the email:
from – Sender’s email address.
to – It is a comma-separated list of emails or an
array of senders’ email ID
subject – Email’s subject
text – The plaintext version of the message (
Buffer, Unicode string, Stream, or an
attachment: ({path: ‘/var/data/…’}))
Now moving towards the final section to send
an email. For that, we will use the sendMail()
method provided by the transport object that
we’ve created above.
mailOptions
callback function- It will be called when
either email is successfully sent or gives an
error.
The sendMail() method will take two
arguments:
Output- Here is the Text Email sent through
NodeMailer.
const mailOptions = {
from: 'sender@gmail.com', // Sender
address
to: 'receiver@gmail.com', // List of
recipients
subject: 'Node Mailer', // Subject line
html: '<h1 style="color:#ff6600;">Hello
People!,
Welcome to Bacancy!</h1>',
attachments: [
{ filename: 'profile.png', path:
'./images/profile.png' }
]
};
Step:7 Sending an Email with
HTML and Attachment
Use the below code snippet for sending an email
with HTML and attachments.
transport.sendMail(mailOptions, function(err,
info) {
if (err) {
console.log(err)
} else {
console.log(info);
}
});
The email contains two fields:
html – The HTML part contains a Buffer,
Unicode string, Stream, or an attachment:
({path: ‘http://…’})
attachments – An array of attachments’ objects.
Attachments can be used for embedding pdf,
images, documents, and many more.
Output- Here is the HTML Email with an
attachment sent through NodeMailer.
Conclusion
So, this was about how to send email using
NodeMailer. I hope the tutorial has assisted you
the way you have expected. You can also try
building the demo application from scratch
with us, add NodeMailer, and start learning!
And don’t forget to explore the NodeMailer
documentation.
If you’re a NodeJS enthusiast, then feel free to
visit NodeJS tutorials, where we have more
tutorials with respective Github repositories
that you can clone and play around with.
Bacancy has skilled developers with
fundamental and advanced NodeJS
development. If you are looking for
consummate NodeJS developers, then without
wasting a minute, contact Bacancy and Hire
NodeJS developers.
Thank You
www.bacancytechnology.com

More Related Content

What's hot

Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarAbir Mohammad
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React NativeEric Deng
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascriptEman Mohamed
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Hands On with Maven
Hands On with MavenHands On with Maven
Hands On with MavenSid Anand
 

What's hot (20)

Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
C# Async Await
C# Async AwaitC# Async Await
C# Async Await
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Node.js
Node.jsNode.js
Node.js
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Hands On with Maven
Hands On with MavenHands On with Maven
Hands On with Maven
 

Similar to Node mailer example how to send email using nodemailer with gmail &amp; mailtrap

Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfKaty Slemon
 
Action Mailer
Action MailerAction Mailer
Action MailerSHC
 
vishal_sharma: python email sending software
vishal_sharma: python email sending software  vishal_sharma: python email sending software
vishal_sharma: python email sending software vishal sharma
 
Packet Tracer WEB & Email
Packet Tracer WEB & Email Packet Tracer WEB & Email
Packet Tracer WEB & Email Mr. FM
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with RailsJames Gray
 
Email Configuration
Email ConfigurationEmail Configuration
Email ConfigurationProdigyView
 
How to implement email functionalities with Mailjet api
How to implement email functionalities with Mailjet apiHow to implement email functionalities with Mailjet api
How to implement email functionalities with Mailjet apiE Boisgontier
 
Install iRedMail on Red Hat Enterprise Linux, CentOS
Install iRedMail on Red Hat Enterprise Linux, CentOSInstall iRedMail on Red Hat Enterprise Linux, CentOS
Install iRedMail on Red Hat Enterprise Linux, CentOSInfoExcavator
 
Install iRedMail on Red Hat Enterprise Linux, CentOS
Install iRedMail on Red Hat Enterprise Linux, CentOSInstall iRedMail on Red Hat Enterprise Linux, CentOS
Install iRedMail on Red Hat Enterprise Linux, CentOSMd Meherab Hossen
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flaskJeetendra singh
 
Using Parse Server to send emails via Mandrill
Using Parse Server to send emails via MandrillUsing Parse Server to send emails via Mandrill
Using Parse Server to send emails via MandrillCharles Ramos
 
Mobilizing Your Rails Application - LA Ruby Conference 2009
Mobilizing Your Rails Application - LA Ruby Conference 2009Mobilizing Your Rails Application - LA Ruby Conference 2009
Mobilizing Your Rails Application - LA Ruby Conference 2009Brendan Lim
 

Similar to Node mailer example how to send email using nodemailer with gmail &amp; mailtrap (20)

Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8
 
Send email
Send emailSend email
Send email
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
EmaiL Parser
EmaiL ParserEmaiL Parser
EmaiL Parser
 
Action Mailer
Action MailerAction Mailer
Action Mailer
 
vishal_sharma: python email sending software
vishal_sharma: python email sending software  vishal_sharma: python email sending software
vishal_sharma: python email sending software
 
Lecture19
Lecture19Lecture19
Lecture19
 
Send Email In Asp.Net
Send Email In Asp.NetSend Email In Asp.Net
Send Email In Asp.Net
 
Packet Tracer WEB & Email
Packet Tracer WEB & Email Packet Tracer WEB & Email
Packet Tracer WEB & Email
 
Ruby
RubyRuby
Ruby
 
How to create mail server in cisco packet tracer
How to create mail server in cisco packet tracerHow to create mail server in cisco packet tracer
How to create mail server in cisco packet tracer
 
Lecture19
Lecture19Lecture19
Lecture19
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
 
Email Configuration
Email ConfigurationEmail Configuration
Email Configuration
 
How to implement email functionalities with Mailjet api
How to implement email functionalities with Mailjet apiHow to implement email functionalities with Mailjet api
How to implement email functionalities with Mailjet api
 
Install iRedMail on Red Hat Enterprise Linux, CentOS
Install iRedMail on Red Hat Enterprise Linux, CentOSInstall iRedMail on Red Hat Enterprise Linux, CentOS
Install iRedMail on Red Hat Enterprise Linux, CentOS
 
Install iRedMail on Red Hat Enterprise Linux, CentOS
Install iRedMail on Red Hat Enterprise Linux, CentOSInstall iRedMail on Red Hat Enterprise Linux, CentOS
Install iRedMail on Red Hat Enterprise Linux, CentOS
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
Using Parse Server to send emails via Mandrill
Using Parse Server to send emails via MandrillUsing Parse Server to send emails via Mandrill
Using Parse Server to send emails via Mandrill
 
Mobilizing Your Rails Application - LA Ruby Conference 2009
Mobilizing Your Rails Application - LA Ruby Conference 2009Mobilizing Your Rails Application - LA Ruby Conference 2009
Mobilizing Your Rails Application - LA Ruby Conference 2009
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfKaty Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfKaty Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfKaty Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfKaty Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfKaty Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfKaty Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfKaty Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfKaty Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfKaty Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfKaty Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfKaty Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfKaty Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfKaty Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfKaty Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfKaty Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfKaty Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfKaty Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfKaty Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfKaty Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfKaty Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
 

Recently uploaded

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Node mailer example how to send email using nodemailer with gmail &amp; mailtrap

  • 1. NodeMailer Example: How to Send Email using NodeMailer with Gmail & Mailtrap www.bacancytechnology.com
  • 2. Ways of communication have evolved over the years. And sending email is considered the most professional and widely used feature in the web area. Emails are used for interacting and communicating with your customers so that they don’t miss any important updates.
  • 4. Most of all, the applications use email as their feature for communicating with the users. Have you ever thought about how applications send emails? If you are looking for an answer for your ‘how,’ then you’re at the right place! In this tutorial, we will learn how to send emails from the Node.JS app with the help of NodeMailer. With the help of the NodeMailer example, we will cover sending emails with basic HTML content and attachments. For setting up the fake SMTP server, we can use Mailtrap or Gmail accounts. In this blog, we will learn how to send email using NodeMailer with both- Mailtrap and Gmail accounts; you can prefer whichever you want to.
  • 6. Zero dependencies on other modules Secure emails delivery HTML content or embedded attachments Unicode support Various transport options besides SMTP NodeMailer is the most famous module used for sending and receiving emails from NodeJS applications. It is a zero dependency module for your NodeJS apps. You can easily send emails as plain text, HTML, or attachments (image, document, etc.). Here are some of the features of NodeMailer that makes it best and popular- Let’s start with our NodeMailer example and learn how to send email using NodeMailer.
  • 7. NodeMailer Example: How to Send Email using NodeMailer
  • 8. There are innumerable modules and packages available for sending emails. From them, NodeMailer is said to be the most favorable and famous that allows you to send emails hassle- free. Follow this step-by-step guide for developing a demo application and implement NodeMailer in your NodeJS application. Step 1: Getting Started Create a new directory and run the npm init command for generating the package.json file. Use these below commands: $ mkdir nodejs-email $ cd nodemailer $ npm init -y
  • 9. Step-2: Install dependencies Install the NodeMailer module using npm: $ npm install nodemailer Install the dotenv package to store user credentials. $ npm install dotenv Create a file named .env having two variables: EMAIL_USERNAME– For account ID EMAIL_PASSWORD– For password
  • 10. Create an app.js file in the directory for the NodeMailer end-point. To keep it simple, we will write the complete code in app.js. You require the below syntax for loading packages: require('dotenv').config(); const nodemailer = require('nodemailer'); Step-3: Using SMTP for Nodemailer Transport SMTP (Simple Mail Transfer Protocol) is used to send emails between various servers. Almost all the email systems are SMTP-based for sending emails over the Internet.
  • 11. let transport = nodemailer.createTransport(options[, defaults]) options – It is an object that is used to connect with any host. defaults – It is an object combining into each message object. With its help, you can define shared options, e.g., setting the default address for email. Nonetheless, for sending a message via our transport, configuring the connection must. Moving forward in our NodeMailer example.
  • 12. Create a brand new Mailtrap account Create new inbox Get your credentials Step:4 Connection with Mailtrap Account We can use Mailtrap- a dummy SMTP server. Rather than testing the demo with your mail and piling the inbox with test and unwanted emails, use Mailtrap as an end-point. If you don’t have a Mailtrap account, follow these steps- Later use the credentials into nodemailer’s transport object.
  • 13. let transport = nodemailer.createTransport({ host: 'smtp.mailtrap.io', port: 2525, auth: { user: process.env.EMAIL_USERNAME, pass: process.env.EMAIL_PASSWORD } }); Keep your username and password inside the .env file and use it here. Step:5 Connection with Gmail Account In case you want to use your Gmail account use the below code snippet. Keep the credentials into the transport object.
  • 14. let transport = nodemailer.createTransport({ host: "smtp.gmail.com", port: 465, secure: true, auth: { user: process.env.EMAIL_USERNAME, pass: process.env.EMAIL_PASSWORD } }); port – if secure is false, it uses 587, by default, and 465 if true host – it’s an IP address/hostname for connecting to (by default to ‘localhost’) auth – it defines authentication data We have discussed both connections over here- Mailtrap and Gmail. You can use any one transport connection at a time for sending an email.
  • 15. Step: 6 Sending an Email with Text const mailOptions = { from: 'sender@gmail.com', // Sender address to: 'receiver@gmail.com', // List of recipients subject: 'Node Mailer', // Subject line text: 'Hello People!, Welcome to Bacancy!', // Plain text body }; transport.sendMail(mailOptions, function(err, info) { if (err) { console.log(err) } else { console.log(info); } }); Note: Before sending an email from your Gmail account, allow non-secure apps for accessing your Gmail account. For that,
  • 16. Go to your Gmail account settings. Enable less secure apps for sending emails from NodeMailer. These are fields of the email: from – Sender’s email address. to – It is a comma-separated list of emails or an array of senders’ email ID subject – Email’s subject text – The plaintext version of the message ( Buffer, Unicode string, Stream, or an attachment: ({path: ‘/var/data/…’})) Now moving towards the final section to send an email. For that, we will use the sendMail() method provided by the transport object that we’ve created above.
  • 17. mailOptions callback function- It will be called when either email is successfully sent or gives an error. The sendMail() method will take two arguments: Output- Here is the Text Email sent through NodeMailer.
  • 18. const mailOptions = { from: 'sender@gmail.com', // Sender address to: 'receiver@gmail.com', // List of recipients subject: 'Node Mailer', // Subject line html: '<h1 style="color:#ff6600;">Hello People!, Welcome to Bacancy!</h1>', attachments: [ { filename: 'profile.png', path: './images/profile.png' } ] }; Step:7 Sending an Email with HTML and Attachment Use the below code snippet for sending an email with HTML and attachments.
  • 19. transport.sendMail(mailOptions, function(err, info) { if (err) { console.log(err) } else { console.log(info); } }); The email contains two fields: html – The HTML part contains a Buffer, Unicode string, Stream, or an attachment: ({path: ‘http://…’}) attachments – An array of attachments’ objects. Attachments can be used for embedding pdf, images, documents, and many more.
  • 20. Output- Here is the HTML Email with an attachment sent through NodeMailer.
  • 22. So, this was about how to send email using NodeMailer. I hope the tutorial has assisted you the way you have expected. You can also try building the demo application from scratch with us, add NodeMailer, and start learning! And don’t forget to explore the NodeMailer documentation. If you’re a NodeJS enthusiast, then feel free to visit NodeJS tutorials, where we have more tutorials with respective Github repositories that you can clone and play around with. Bacancy has skilled developers with fundamental and advanced NodeJS development. If you are looking for consummate NodeJS developers, then without wasting a minute, contact Bacancy and Hire NodeJS developers.