Guides
Last Updated Aug 03, 2023

Node.js: Send Email from Your Server

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Having a way for a user to send an email from inside your app is important. Users need a way to get in touch with you, and contact forms are useful for generating leads and building email lists.

There are many services that will handle the business of sending emails for you. Instabug, for example, is a React Native plugin that handles submitting bug reports. There are many options for sending emails directly from your Javascript front end.

For sending email from your back end, a transactional email service like Sendgrid or Mailgun is a great option that is highly scalable and handles the complexity of running an SMTP server.

If you don't want to pay for a service like Sendgrid, another option is to run your own SMTP server. However, this can be difficult to maintain and you will need to constantly monitor your service, so it is not recommended when there are so many services out there that will do the job for you, and do it better.

In this article, we'll take a look at how to send emails from your back end using Nodemailer and Mailtrap. We'll also look at adding an additional security step by validating and verifying all email addresses through the AbstractAPI Free Email Validation API.

Let’s send your first free
API
Email Verification API
call
See why the best developers build on Abstract
Get your free api

What is SMTP?

SMTP (or Simple Mail Transfer Protocol) is the network communication layer that manages email communications. SMTP outlines how emails should be sent and received, the same way HTTP (Hyper Text Transfer Protocol) outlines how data packages should be sent and received on the web.

An SMTP server handles SMTP traffic. Emails are sent from email clients to SMTP servers, which handle the transferring of emails to other SMTP servers and ultimately to other email clients.

SMTP servers are important for preventing spam. They also provide security and prevent hackers and other bad actors from invading our emails and ruining our days. 

Here's a brief overview of the process of sending an email through SMTP:

  1. The server receives email information from a client (usually on Port 25.) The client is the email service from which you send email, like a Gmail account or a Yahoo account.
  2. It breaks the address of both sender and recipient into two parts: the username and the domain. 
  3. For example, in the address abstractapi@gmail.com, the username is abstractapi and the domain is gmail.com
  4. It examines the domain of the sender and the domain of the recipient. If both are under the same domain (i.e. gmail.com) it sends the email via that domain’s preferred method (i.e. POP or IMAP.)
  5. If the domain of the sender and recipient are different, the server checks to see that the sender’s email address is an active and valid email. This prevents spam.
  6. If the sender’s address is valid, the server sends the email data to the recipient’s SMTP server. That server handles delivering the email to the recipient.


SMTP can only be accessed by backend servers. You cannot make an SMTP request from a frontend Javascript client directly.

That's because apps that runs in the browser aren't allowed access to Port 25. This is to prevent Javascript and other frontend apps from being able to spam people. If you're running a serverless frontend like a Gatsby site, you'll need to send your email data to an SMTP server or transactional email service.

If you run your own backend, you can configure your own server with an SMTP port.

Sending Emails Using Nodemailer and Mailtrap

Nodemailer is a lightweight module that makes sending emails from your application straightforward. It has been around since 2010, so it's well documented and supported. There are zero dependencies, and the module emphasizes security, putting a heavy focus on RCE vulnerabilities.

Nodemailer supports emojis, HTML content, attachments and embedded images. You can autogenerate test accounts for development purposes through Ethereal.email.

Mailtrap is a fake SMTP server that you can use during development and testing to avoid cluttering your real SMTP service with test data. Once you finish setup and testing, you can swap out the credentials in the Nodemailer module with the real credentials for your Sendgrid, Mailgun or Mailchimp API.

Let's dive in to the installation and setup. We'll assume you already know how to spin up a Node application. If you don't, this article has a pretty good walkthrough that will get you started with Node and Express.

Get a Mailtrap Account

Go to the Mailtrap homepage and click "Sign Up for Free." You get 500 test emails per month with a free account. From there, pricing increases to $9/month if you need higher send limits or additional users.

On the next page, choose your preferred sign-in method to create an account.

Once you finish the sign up process, you'll be taken to your Mailtrap dashboard. You'll see a code snippet for a curl request to test the API, which will include your user number and the SMTP url.

You won't need the API key for this tutorial. Instead, click on the "Integrations" dropdown menu and select "Nodemailer."

You'll now see the credentials you need for your Nodemailer setup. Copy this somewhere for the next step.

Install Nodemailer

Add the Nodemailer dependency using your preferred package manager. The following command uses NPM install.



npm install nodemailer

Create the Nodemailer Transporter Object

Create a new js file called email.js in the project directory. This will be where we keep all our email service logic. Pull in nodemailer and copy the code snippet provided by Mailtrap.



const nodemailer = require("nodemailer");

const transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "YOUR USER NUMBER",
    pass: "YOUR PASSWORD"
  }
});

Create a Message Object

Next, we need to create a message to test the transporter object. This will contain the information about our sender email and receivers, subject, and the email body.

The transporter object has a sendMail method that accepts an email message and sends it to the intended recipient.



const message = {
         from: "your_email_account@domain.com",
         to: "recipient_email_account@domain.com",
         subject: "Hello!",
         text: "This is a test of Mailtrap and Nodemailer. "
}
    
transport.sendMail(message, (err, info) => {
    if (err) {
        console.log(err)
    } else {
        console.log(info);
    }
});

We can easily test the sendMail method by running the following command in the terminal



node email.js

If you've set everything up correctly, you should see the following output in your terminal:



{
  accepted: [ 'recipient_email_account@gmail.com' ],
  rejected: [],
  envelopeTime: 281,
  messageTime: 220,
  messageSize: 323,
  response: '250 2.0.0 Ok: queued',
  envelope: {
    from: 'your_email_account@domain.com',
    to: [ 'recipient_email_account@domain.com' ]
  },
  messageId: ''
}

Go to your Mailtrap account and click on "Email Logs" to see the information about the sent email.

Add Email Validation with AbstractAPI

While SMTP does a great job of managing spam, it's always a good idea to add a validation or verification step to your email sending procedure. A service like AbstractAPI provides free validation for up to 100 requests.

AbstractAPI checks for syntax errors and misspelled domains, checks MX records, look for role-based accounts, free email accounts, and disposable accounts, and does a deep-level SMTP check.

Let's add a validation step to our email.js file.

Acquire an API Key

Navigate to the AbstractAPI Email validator homepage and click on the blue "Get Started" button.

You’ll be asked to sign up by providing a valid email address and password. If you've already signed up, you may need to log in. Once you’re in, you’ll land on the API’s dashboard, where you’ll see your API key and links to documentation and pricing.

Use Your API Key to Send a Request to the API

We'll use Fetch to send a GET request to the AbstractAPI endpoint. Fetch is now available as a global in Node, just like it is in Javascript that runs in the browser.

Write a function called sendEmailValidationRequest that accepts an email as a parameter and sends it to the API. 



const apiKey = 'YOUR_API_KEY';
const apiURL = 'https://emailvalidation.abstractapi.com/v1/?api_key=' + apiKey

   const sendEmailValidationRequest = async (email) => {
       try {
           const response = await fetch(apiURL + '&email=' + email);
           const data = await response.json();
           console.log(data);
       } catch (error) {
           throw error;
       }
   }

Next, let's add this step to our code before we send the request to Mailtrap. Since we're now going to be doing some conditional logic and a couple of steps, let's wrap everything in a closing main() function to keep stuff tidy and out of the global scope.

The following code demonstrates.



const nodemailer = require("nodemailer");

const apiKey = 'YOUR_API_KEY';
const apiURL = 'https://emailvalidation.abstractapi.com/v1/?api_key=' + apiKey


async function main()
{
    const sendEmailValidationRequest = async (email) => {
       try {
           const response = await fetch(apiURL + '&email=' + email);
           const data = await response.json();
           return data.is_valid_format.value;
       } catch (error) {
           throw error;
       }
    }
    const isValidSenderEmail = endEmailValidationRequest("your_email_account@domain.com");
    if (isValidSenderEmail) {
        const transport = nodemailer.createTransport({
            host: "smtp.mailtrap.io",
            port: 2525,
            auth: {
                user: "YOUR USER ID",
                pass: "YOUR PASSWORD"
            }
        });

        const message = {
                from: "your_email_account@domain.com",
                to: "recipient_email_account@domain.com",
                subject: "Hello!",
                text: "This is a test of Mailtrap and Nodemailer. "
        }
        
        transport.sendMail(message, (err, info) => {
            if (err) {
                console.log(err)
            } else {
                console.log(info);
            }
        });
    } else {
        console.error("Sender's email address is not valid.")
    }

}  
 
main().catch(console.error);

Note that in this example, we're only checking the value of the is_valid_format field that we get back from AbstractAPI. That means that the only criteria we want the email to meet is that it doesn't have any syntax errors.

The JSON response object that AbstractAPI returns to us has much more information in it that we could use. The complete object looks something like this:



{
  "email": "email@domain.com",
  "autocorrect": "",
  "deliverability": "DELIVERABLE",
  "quality_score": "0.80",
  "is_valid_format": {
    "value": true,
    "text": "TRUE"
  },
  "is_free_email": {
    "value": false,
    "text": "FALSE"
  },
  "is_disposable_email": {
    "value": false,
    "text": "FALSE"
  },
  "is_role_email": {
    "value": false,
    "text": "FALSE"
  },
  "is_catchall_email": {
    "value": true,
    "text": "TRUE"
  },
  "is_mx_found": {
    "value": true,
    "text": "TRUE"
  },
  "is_smtp_valid": {
    "value": true,
    "text": "TRUE"
  }
}

To do a more thorough validation check, we could use all of the fields in the returned JSON object to determine whether we think the email is valid or not. We can write a helper function to run this check for us and return a boolean value.

The following code demonstrates this.



const isValid = (validatedResponseObject) => {
    const {
        is_valid_format,
        is_free_email,
        is_disposable_email,
        is_role_email,
        is_catchall_email,
        is_mx_found,
        is_smtp_valid
    } = validatedResponseObject;
    if (is_valid_format && is_mx_found && is_smtp_valid) {
        if (!is_free_email && !is_disposable_email && !is_role_email && !is_catchall_email) {
            return true;
        } else {
            return false;
        }
    }
	return false;
}

Now, replace our validation step with our new helper function



    const sendEmailValidationRequest = async (email) => {
       try {
           const response = await fetch(apiURL + '&email=' + email);
           const data = await response.json();
           return isValid(data);
       } catch (error) {
           throw error;
       }
    }

That's it! We've now validated the sender's email address and used the result of that validation check to determine whether or not we should use it to send emails.

Conclusion

In this article, we looked at how to use Nodemailer and Mailtrap to send emails from a back end. We also incorporated the AbstractAPI Free Email Validation API to validate the sender's email before using it.

There is a lot we can do to improve this setup and make it more robust, including improving our error handling or allowing for retries using something like a refresh token.

There are also more configuration options for Nodemailer and Mailtrap that we haven't explored. And remember, Mailtrap is only intended for testing emails. You'll need to swap emails out for a real email service to send emails in production.

This is a good start at getting your web applications set up to handle sending and receiving emails.

FAQs

Can Node JS Send Email?

Yes, you can send mail from a web application that uses Node JS on the back end. While it's not recommended to try and run your own SMTP server, you can easily integrate with a transactional email service that will provide an SMTP server for you.

Many of the best email services, like Mailgun and Sendgrid, have their own SDKs. If you happen to be using a service that doesn't have its own SDK, you can use Nodemailer to send emails to the service.

How do I Send an Email With Attachment: Node?

Use Nodemailer or an SMTP provider like Mailgun or Sendgrid to send email data from your back end. The Nodemailer module has an attachments field that allows you to add attachments to any email you send through the service. SMTP provider SDKs also include an attachments option.

Make sure to check your SMTP provider to see what the attachment limits are. Most providers will limit attachment size at the free tier, but you can increase attachment limits by paying per month.

How Do I Use SMTP in Node JS?

It is possible to configure and run your own SMTP server for a web application, however, it's recommended to rely on a service like Sendgrid or Mailgun to do this part for you. Sendgrid and Mailgun allow you to spin up an SMTP server and then request it from your back end.

You can use Nodemailer to send the email requests to Sendgrid, or you can use the Sendgrid SDK.

4.6/5 stars (12 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Email Verification API
API
key now
Validate email instantly using Abstract's email verification API.
get started for free

Related Articles

Get your free
API
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required