Quick Summary
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.
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.
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.
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.
Want to develop the best and most high-performance NodeJS apps?
Contact Bacancy for proficient and dedicated developers with excellent problem-solving skills. Without wasting your time hire Node.js developer from us!
Create a new directory and run the npm init command for generating the package.json file. Use these below commands:
Install the NodeMailer module using npm:
Install the dotenv package to store user credentials.
Create a file named .env having two variables:
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:
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.
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.
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.
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.
const mailOptions = { from: '[email protected]', // Sender address to: '[email protected]', // 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,
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.
The sendMail() method will take two arguments:
Output- Here is the Text Email sent through NodeMailer.
Use the below code snippet for sending an email with HTML and attachments.
const mailOptions = { from: 'sender@gmail.com', // Sender address to: 'receiver@gmail.com', // List of recipients subject: 'Node Mailer', // Subject line html: ' Hello People!, Welcome to Bacancy!
', attachments: [ { filename: 'profile.png', path: './images/profile.png' } ] }; 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.
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.
Absolutely! There’s no such restriction about not using NodeMailer with a Gmail account. Read the above tutorial and implement NodeMailer in your application with your Gmail account!
Simple Mail Transfer Protocol, SMTP, as the name suggests, is used for sending and receiving emails over the Internet. It listens to port 25 and runs on TCP/IP.
NodeMailer is an open-source module that you can use for free.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.