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?
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 popularZero dependencies on other modules Secure emails delivery HTML content or embedded attachments Unicode support Various transport options besides SMTP 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 hasslefree. 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.
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 stepsCreate a brand new Mailtrap account Create new inbox Get your credentials 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 hereMailtrap 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.
The sendMail() method will take two arguments: mailOptions callback function- It will be called when either email is successfully sent or gives an error. Output- Here is the Text Email sent through NodeMailer.
Step:7 Sending an Email with HTML and Attachment 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: '<h1 style="color:#ff6600;">Hello People!, Welcome to Bacancy!</h1>', 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.
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