Skip to content

Latest commit

 

History

History
451 lines (355 loc) · 12.7 KB

File metadata and controls

451 lines (355 loc) · 12.7 KB

ZeroBounce JavaScript API v2

WE DO NOT RECOMMEND USING THIS SDK ON A FRONT-END ENVIRONMENT AS THE API KEY WILL BE VISIBLE

This is a JavaScript wrapper class for the ZeroBounce API v2.

INSTALLATION

npm install @zerobounce/zero-bounce-sdk

Node.js

The SDK uses the global fetch API for HTTP requests. Node.js 18 or later is required when running in Node; older versions do not provide fetch and will throw (e.g. TypeError: fetch failed or fetch is not defined). If you must use Node 16 or older, polyfill fetch before using the SDK, for example:

global.fetch = require('node-fetch');
const ZeroBounceSDK = require('@zerobounce/zero-bounce-sdk');
// ...

Testing

  • npm test — Runs unit tests (Jest) and TypeScript type checks.
  • npm run test:unit — Unit tests only.
  • npm run test:types — Type-checks the declaration file and a TypeScript consumer.
  • npm run dts-check — Validates zeroBounceSDK.d.ts.
  • npm run build && npm run test:smoke — Builds the bundle and runs a smoke test against dist/.

TypeScript

The package includes TypeScript declaration files. You can use it in TypeScript or JavaScript with full IntelliSense and type checking:

import ZeroBounceSDK from '@zerobounce/zero-bounce-sdk';
import type { ValidateEmailOptions, ValidateBatchEmailItem } from '@zerobounce/zero-bounce-sdk';

const zeroBounce = new ZeroBounceSDK();
zeroBounce.init(process.env.ZEROBOUNCE_API_KEY!);

// Typed options
const opts: ValidateEmailOptions = { ip_address: '127.0.0.1', timeout: 10 };
const result = await zeroBounce.validateEmail('user@example.com', opts);

// Status constants
if (result?.status === ZeroBounceSDK.ZBValidateStatus.VALID) {
  // ...
}
// Bulk getfile: ZeroBounceSDK.ZBDownloadType.PHASE_1 | PHASE_2 | COMBINED

USAGE

Add the script

<script src="<PATH_TO_SCRIPT/zeroBounceSDK.js"></script>
<script>
const zeroBounce = new ZeroBounceSDK();
</script>

OR

Add npm module

const ZeroBounceSDK = require('@zerobounce/zero-bounce-sdk')

const zeroBounce = new ZeroBounceSDK();

Initialize the sdk with your api key:

zeroBounce.init("<YOUR_API_KEY>", ZeroBounceSDK.ApiURL.DEFAULT_API_URL);

NOTE: all the methods are asynchronous they have to be used with async / await or .then.catch

Examples

Then you can use any of the SDK methods, for example:

  • Check how many credits you have left on your account
try {
  const response = await zeroBounce.getCredits();
} catch (error) {
  console.error(error);
}
  • Validate an email address
const email = "<EMAIL_ADDRESS>"; // The email address you want to validate
const ip_address = "127.0.0.1"; // The IP Address the email signed up from (Optional)

try {
  const response = await zeroBounce.validateEmail(email, ip_address);
} catch (error) {
  console.error(error);
}
  • Get api usage from a start date to an end date
const startDate = "2018-01-01"; // The start date of when you want to view API usage
const endDate = "2023-12-12"; // The end date of when you want to view API usage

try {
  const response = await zeroBounce.getApiUsage(startDate, endDate);
} catch (error) {
  console.error(error);
}
  • Validate a list of emails
const emailBatch = [
  { email_address: "<EMAIL_ADDRESS>" },
  { email_address: "<EMAIL_ADDRESS>" },
]; // an array containing a list of email objects {email_address: "example@example.com"}

try {
  const response = await zeroBounce.validateBatch(emailBatch);
} catch (error) {
  console.error(error);
}
  • Get data about an email activity
const email = "<EMAIL_ADDRESS>"; // The email address you want to get the activity for

try {
  const response = await zeroBounce.getEmailActivity(email);
} catch (error) {
  console.error(error);
}
  • Send a csv file containing email addresses to be validated
// Parameters
// ----------
// file: File
//     The csv or txt file to be submitted.
// email_address_column: number
//     The column index of the email address in the file. Index starts from 1.
// return_url: str or null (Optional)
//     The URL will be used to call back when the validation is completed.
// first_name_column: number or null (Optional)
//     The column index of the first name column.
// last_name_column: number or null (Optional)
//     The column index of the last name column.
// gender_column: number or null (Optional)
//     The column index of the gender column.
// ip_address_column: number or null (Optional)
//     The IP Address the email signed up from.
// has_header_row: Boolean (Optional)
//     If the first row from the submitted file is a header row.
// remove_duplicate: Boolean (Optional)
//     If you want the system to remove duplicate emails.
// allowPhase2: Boolean (Optional)
//     When set, sends allow_phase_2 (validation bulk only). See v2 send file API.
const payload = {
  file: "<FILE>",
  email_address_column: "<NUMBER_OF_COLUMN>", //example 3
  return_url: "<RETURN_URL>", // (Optional)
  first_name_column: "<NUMBER_OF_COLUMN>", //example 3 (Optional)
  last_name_column: "<NUMBER_OF_COLUMN>", //example 3 (Optional)
  gender_column: "<NUMBER_OF_COLUMN>", //example 3 (Optional)
  ip_address_column: "<NUMBER_OF_COLUMN>", //example 3 (Optional)
  has_header_row: true / false, // (Optional)
  remove_duplicate: true / false, // (Optional)
  allowPhase2: true, // (Optional)
};

try {
  const response = await zeroBounce.sendFile(payload);
} catch (error) {
  console.error(error);
}

Bulk validation uses https://bulkapi.zerobounce.net/v2. See v2 send file, v2 file status, and v2 get file.

Bulk API v2: ZeroBounceSDK.ZBDownloadType provides PHASE_1, PHASE_2, and COMBINED for getFile / getScoringFile. File status responses may include file_phase_2_status. For getFile, pass an optional second argument { downloadType, activityData } (validation only for activityData; getScoringFile does not send activity_data). If the API returns a JSON error body with HTTP 200, the SDK returns a parsed object instead of treating the body as CSV.

  • Send a csv file containing email addresses to get the scoring of the emails
// Parameters
// ----------
// file: File
//     The csv or txt file to be submitted.
// email_address_column: number
//     The column index of the email address in the file. Index starts from 1.
// return_url: str or null (Optional)
//     The URL will be used to call back when the validation is completed.
// has_header_row: Boolean (Optional)
//     If the first row from the submitted file is a header row.
// remove_duplicate: Boolean (Optional)
//     If you want the system to remove duplicate emails.
const payload = {
  file: "<FILE>",
  email_address_column: "<NUMBER_OF_COLUMN>", //example 3
  return_url: "<RETURN_URL>", // (Optional)
  has_header_row: true / false,
  remove_duplicate: true / false, // (Optional)
};

try {
  const response = await zeroBounce.sendScoringFile(payload);
} catch (error) {
  console.error(error);
}
  • The completion status of a previously sent file
const fileId = "<FILE_ID>"; // The id of a previously sent file

try {
  const response = await zeroBounce.getFileStatus(fileId);
} catch (error) {
  console.error(error);
}
  • The completion status of a previously sent scoring file
const fileId = "<FILE_ID>"; // The id of a previously sent file

try {
  const response = await zeroBounce.getScoringFileStatus(fileId);
} catch (error) {
  console.error(error);
}
  • Get the file with the validated data
const fileId = "<FILE_ID>"; // The id of a previously sent file

try {
  const response = await zeroBounce.getFile(fileId);
} catch (error) {
  console.error(error);
}

Optional query parameters (see v2 get file API):

await zeroBounce.getFile(fileId, {
  downloadType: ZeroBounceSDK.ZBDownloadType.COMBINED,
  activityData: true,
});
  • Get the file with the scoring data
const fileId = "<FILE_ID>"; // The id of a previously sent file

try {
  const response = await zeroBounce.getScoringFile(fileId);
} catch (error) {
  console.error(error);
}
await zeroBounce.getScoringFile(fileId, {
  downloadType: ZeroBounceSDK.ZBDownloadType.PHASE_2,
});
  • Delete the file with the validated data
const fileId = "<FILE_ID>"; // The id of a previously sent file

try {
  const response = await zeroBounce.deleteFile(fileId);
} catch (error) {
  console.error(error);
}
  • Delete the file with the scoring data
const fileId = "<FILE_ID>"; // The id of a previously sent file

try {
  const response = await zeroBounce.deleteScoringFile(fileId);
} catch (error) {
  console.error(error);
}
  • ####### Email finder - Test a variety of patterns and combinations in real time until it identifies a valid business email.
// Parameters
// ----------
// domain: String
//     The email domain for which to find the email format. 
// company_name: String
//     The company name for which to find the email format.
// first_name: String
//     The first name of the person whose email format is being searched.
// middle_name: String or null (Optional)
//     The middle name of the person whose email format is being searched.
// last_name: String or null (Optional)
//     The last name of the person whose email format is being searched.

const domainPayload = {
  domain: "<DOMAIN>",
  first_name: "<FIRST_NAME>",
  middle_name: "<MIDDLE_NAME>",
  last_name: "<LAST_NAME>"
}

const companyNamePayload = {
  company_name: "<COMPANY_NAME>",
  first_name: "<FIRST_NAME>",
  middle_name: "<MIDDLE_NAME>",
  last_name: "<LAST_NAME>"
}

try {
  const domainResponse = await zeroBounce.findEmailByDomain(domainPayload);
  const companyNameResponse = await zeroBounce.findEmailByCompanyName(companyNamePayload);
} catch (error) {
  console.error(error);
}
  • ####### Domain Search - Find the domain based on a given domain name or company name
// Parameters
// ----------
// domain: String
//     The domain name for which to find the email format. 
// company_name: String
//     The company name for which to find the email format.

const domainPayload = {
  domain: "<DOMAIN>"
}

const companyNamePayload = {
  company_name: "<COMPANY_NAME>"
}

try {
  const domainResponse = await zeroBounce.findEmailFormatByDomain(domainPayload);
  const companyNameResponse = await zeroBounce.findEmailFormatByCompanyName(companyNamePayload);
} catch (error) {
  console.error(error);
}

Any of the following email addresses can be used for testing the API, no credits are charged for these test email addresses:

You can use this IP to test the GEO Location in the API.

  • 99.110.204.1

Development

Run tests with Docker

From the parent repository root (the folder that contains all SDKs and docker-compose.yml):

docker compose build javascript
docker compose run --rm javascript

The repo includes a .dockerignore so the image build context stays small (no node_modules / coverage from the host).

You can also run docker build -t zerobounce-javascript-sdk:test . from this directory.

Run tests (local)

After checking out the repo run tests

npm test

You should see an output like this

Test Suites: 1 passed, 1 total
Tests:       58 passed, 58 total
Snapshots:   0 total
Time:        2.596 s, estimated 3 s
Ran all test suites.

Publish

See the sdk-docs (npm) guide in the SDKs repo for build and npm publish steps.