How to Send Emails with Node.js

How to Send Emails with Node.js

How to Send Emails with Node.js - In this tutorial you'll learn how to send emails with HTML content and attachments using the nodemailer module, as well as set up Mailtrap, a fake SMTP server, for testing your code.

In this tutorial you'll learn how to send emails with HTML content and attachments using the nodemailer module, as well as set up Mailtrap, a fake SMTP server, for testing your code.

Introduction

Email is one of the most used tools for communication in web applications because it helps you reach your users directly, build your brand, or send general notifications.

So, you are thinking about sending emails from your next great Node.js application. You are in the right place!

Prerequisites

To follow along, you will need to have Node.js and npm (Node Package Manager) installed locally.

To test sending emails from a local development machine, without having to configure a server, we will be using Mailtrap.

Getting Started

There are many Node.js modules for sending e-mails. Amongst them, nodemailer is the most popular choice. It is a module that gives you the ability to easily send emails without hassle.

Let's go ahead and create a new folder and a new package.json file with the npm init command:

$ mkdir nodejs-email
$ cd nodejs-email
$ npm init -y

The -y flag provided will skip the step-by-step tool to scaffold out your project.

Now let's install the nodemailer module using npm:

$ npm install nodemailer

With the modle ready for use, let's create an index.js file in our project directory.

In Node.js, the require syntax is used to load modules in to your code:

const nodemailer = require('nodemailer');

Using SMTP for Nodemailer Transport

The Simple Mail Transfer Protocol (SMTP) is a protocol for sending e-mail messages between servers. Most e-mail systems that send mail over the Internet supports SMTP based sending.

And guess what? SMTP is the main transport used by nodemailer for delivering messages.

Creating a nodemailer transport is as easy as calling the following method with a few parameters:

let transport = nodemailer.createTransport(options[, defaults])

However, to actually send a message through our transport, we have to configure the connection first.

Testing our Code with Mailtrap

Mailtrap is a "fake SMTP server" used for development purposes. Instead of having to test your code with your own email account, and potentially flooding your inbox with test emails, you can instead use Mailtrap as the endpoint.

Create a new account on Mailtrap if you don't already have one, and then create a new inbox and get your credentials:

Now, all we need to do is put the credentials into nodemailer's transport object:

let transport = nodemailer.createTransport({
    host: 'smtp.mailtrap.io',
    port: 2525,
    auth: {
       user: 'put_your_username_here',
       pass: 'put_your_password_here'
    }
});

With all of that set up, we can go ahead and send our first test email:

const message = {
    from: '[email protected]', // Sender address
    to: '[email protected]',         // List of recipients
    subject: 'Design Your Model S | Tesla', // Subject line
    text: 'Have the most fun you can in a car. Get your Tesla today!' // Plain text body
};
transport.sendMail(message, function(err, info) {
    if (err) {
      console.log(err)
    } else {
      console.log(info);
    }
});

Ta-da, that's it!

Sending an HTML Email

While the previous example does the job just fine, it's what some may call "boring".

Nowadays, emails tend to be styled, colorful, with big buttons and exciting and engaging visuals. To achieve this, we embed HTML into our emails.

You can create thse HTML emails and send them with nodemailer just as easily as you could send a plain text email. All it takes is to use the html parameter in the message object instead of text:

const message = {
    from: '[email protected]',
    to: '[email protected]',
    subject: 'Design Your Model S | Tesla',
    html: '<h1>Have the most fun you can in a car!</h1><p>Get your <b>Tesla</b> today!</p>'
};

Although this example is quite simple, only including a <h1><p>, and <b> tag, you can include much, much more.

Keep in mind that you can also send both HTML and plain text in a single email by providing both parameters. With both versions in your email message, the recipient's email client can then choose which one to display.

Sending Email with an Attachment

There are countless reasons why you might want to include an attachment in your email, like sending pictures, spreadsheets for work, or videos.

As another example, if you run an e-commerce website, for example, you might want to send receipts to your customers:

const nodemailer = require("nodemailer");

let transport = nodemailer.createTransport({
    // ...
});

const message = {
    from: '[email protected]',
    to: '[email protected]',
    subject: 'Design Your Model S | Tesla',
    html: '<h1>Have the most fun you can in a car!</h1><p>Get your <b>Tesla</b> today!</p>',
    attachments: [
        { // Use a URL as an attachment
          filename: 'your-testla.png',
          path: 'https://media.gettyimages.com/photos/view-of-tesla-model-s-in-barcelona-spain-on-september-10-2018-picture-id1032050330?s=2048x2048'
      }
    ]
};
transport.sendMail(message, function (err, info) {
    // ...
 });

And you can use a file on disk as an attachment too. They don't need to be web-based.

Conclusion

You can now easily send personalized emails in your Node.js code using the nodemailer module. And don't forget, the nodemailer documentation is your best friend for learning about the more advanced options.

Originally published by Guest Contributor at stackabuse.com

node-js javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.