Dev Life
From time to time, people on your mailing list might change jobs or email service providers. When they do, their emails change too, leaving invalid addresses on your list. These invalid emails can lead to high bounce rates, which harms your sender reputation and increases the chance of being blacklisted as spam.
Email validation helps prevent invalid emails by ensuring your emails reach real, active inboxes. By regularly verifying email addresses, you reduce the chances of being bounced, protect your reputation with internet service providers (ISPs), and increase the overall deliverability of your campaigns.
If you’re looking to validate a batch of email addresses, Mailgun offers a bulk email validation API that can help you do just that. In this tutorial, you’ll learn how to efficiently verify large lists of email addresses in Node.js applications with Mailgun and integrate the process into your application to ensure high deliverability.
To follow along with this tutorial, you’ll need:
To verify emails with Node.js using the Mailgun API, you have to create a mailing list and add the emails you want to validate. You can then start a validation job on the mailing list and retrieve the results. But, before you can make requests to the Mailgun API, you need your authentication details from your dashboard. You also need to set up and verify a custom domain to create a mailing list.
The Mailgun API authorizes requests using HTTP Basic Auth, which requires that you include a username and password in your Authorization header. To obtain the required details, log in to your Mailgun account, click the dropdown icon at the top right of your screen, and click API Security in the menu:
On the API Security page, click the Add new key button to reveal a modal with a form. Fill out the description on the form, click Create Key, copy the API key, and store it securely; this is your password, and you can only see it once:
Next, you can choose to add a custom domain to your Mailgun account and verify it. This step is optional and is only required in production environments. For this tutorial, you’ll use the default domain provided by Mailgun, which you can find by navigating to Send > Sending > Domains:
Note the default domain name; you’ll need it to create a mailing list.
After retrieving your authentication details and adding a custom domain (or noting the default), it’s time to set up a Node.js development environment where you’ll make requests to the Mailgun API.
To set up a Node.js development environment, first create a new project directory and cd into it by running the following command:
mkdir bulk-email-validation && cd bulk-email-validation
Then, initialize npm in your project by running this command:
npm init -y
Run the following command to install the required dependencies:
npm install axios dotenv form-data
The installed dependencies include the following:
After installing these dependencies, create an index.js file and a .env file. In your .env file, store the following variables and replace the placeholder values with their actual values:
MAILGUN_USERNAME = api
MAILGUN_PASSWORD = <API_KEY>
The value of your username must be api.
In your index.js file, add the following code block to import all the required dependencies and initialize dotenv:
const axios = require("axios");
const FormData = require("form-data");
const fs = require("node:fs");
const dotenv = require("dotenv");
dotenv.config();
This code block imports the dependencies required to make requests to the Mailgun API. In addition to the packages you installed earlier, the imports include the Node.js fs module, which you need to create a readable stream to the file containing your email list.
Now that your development environment is ready, you can validate email addresses in a mailing list.
As mentioned in the prerequisites, to use the bulk email validation service with Mailgun, you must have a paid account.
To create a validation job with the Mailgun API, you need to make a POST request to https://api.mailgun.net/v4/address/validate/bulk/${listId}, where listId is any arbitrary value you assign to the validation job.
This endpoint accepts a form with a CSV file containing the email addresses you want to validate. The CSV file’s column header for emails needs to be either email or email_address, and the format must be either raw CSV or gzip. You can include an unlimited number of email addresses in the file; however, the file size cannot exceed 25 MB.
The form key for the CSV file must be file, and the value must be a readable stream to the file path of your CSV file.
You can add the code block below to your index.js file to implement a function to create a bulk validation job:
const createBulkValidationJob = async (listId) => {
try {
// Create a new form data object
const form = new FormData();
// Add the file to the form
form.append("file", fs.createReadStream("PATH_TO_CSV_FILE"));
const response = await axios.post(
`https://api.mailgun.net/v4/address/validate/bulk/${listId}`,
form,
{
headers: {
...file.getHeaders(),
Authorization:
"Basic " +
Buffer.from(
`${process.env.MAILGUN_USERNAME}:${process.env.MAILGUN_PASSWORD}`
).toString("base64"),
},
}
);
console.log(response.data);
} catch (error) {
console.error(error);
}
};
Calling this function with a listId should return a response similar to this:
{
id: 'validation', // Arbitrary value you assigned to the validation job
message: 'The validation job was submitted.'
}
Validating a mailing list takes time; to get the validation results, you have to make a request to the API with the id of your validation job.
To fetch the results of a validation job, you need to make a GET request to https://api.mailgun.net/v4/address/validate/bulk/${listId}, where the listId is the id you assigned to your validation job.
Add the following code block to your index.js file to implement a function to fetch your validation results:
const getValidationResults = async (listId) => {
try {
const response = await axios.get(
`https://api.mailgun.net/v4/address/validate/bulk/${listId}`,
{
headers: {
Authorization:
"Basic " +
Buffer.from(
`${process.env.MAILGUN_USERNAME}:${process.env.MAILGUN_PASSWORD}`
).toString("base64"),
},
}
);
console.log(response.data);
} catch (error) {
console.error(error);
}
};
Calling this function with a listId should return a response like this:
{
created_at: 1728170695,
download_url: {
"csv": "https://s3.aws-example.com/downloads/bulk_validation_oct_2024.csv.zip",
"json": "https://s3.aws-example.com/downloads/bulk_validation_oct_2024.json.zip"
},
id: 'validation',
quantity: 10,
records_processed: 10,
status: 'uploaded',
summary: {
result: {
catch_all: 0,
deliverable: 3,
do_not_send: 0,
undeliverable: 1,
unknown: 6
},
risk: { high: 1, low: 3, medium: 0, unknown: 6 }
}
}
created_at
: A timestamp of when the job was completed (1728170695).download_url
: Links to download the results in CSV and JSON formats.Quantity:
The total number of emails processed (10).Status
: The validation job status (uploaded).Result
: The outcome of email validation:deliverable
: Three addresses are valid and deliverable.do_not_send
: No addresses are flagged as “do not send.”undeliverable
: One address is invalid or undeliverable.unknown
: Six addresses couldn’t be verified.Risk
: A breakdown of email addresses by risk:
high
: One address is high-risk and likely undeliverable or problematic.low
: Three addresses are considered low-risk and safe to use.medium
: No addresses are medium-risk and might require caution.unknown
: Six addresses couldn’t be classified.When using the Mailgun API for bulk email validation, you may encounter a few common errors. Here’s a breakdown of these errors and tips on how to troubleshoot them:
To ensure your bulk validation jobs work as expected, here are a few best practices you can follow:
In this tutorial, you explored how to verify emails using Node.js and the Mailgun API. You learned how to create mailing lists, add members to those lists, and validate the email addresses in bulk.
Regular bulk email validation can significantly improve your email deliverability rates, maintain a clean, effective mailing list, ensure your messages reach their intended recipients, and help you maintain a good sender reputation.