Skip to content

Latest commit

 

History

History
531 lines (443 loc) · 19.9 KB

documentation.md

File metadata and controls

531 lines (443 loc) · 19.9 KB

REQUIREMENTS

  • CMake 3.20 or newer.
  • A C++20 compiler to build the library: its CMakeLists.txt compiles the ZeroBounce target (and its fetched dependencies) as C++20.
  • C++17 or newer for your own code that includes the headers. They use std::optional and include libcpr's headers, which need C++17. The ZeroBounce target requires C++17 of every target that links it (target_compile_features(ZeroBounce PUBLIC cxx_std_17)), so CMake compiles a target set to C++14 or older as C++17.
  • On Linux and macOS, OpenSSL with its development files (for example libssl-dev on Linux, or Homebrew's openssl@3 on macOS; pass -DOPENSSL_ROOT_DIR=... if CMake does not find it): libcpr builds its bundled libcurl with HTTPS through OpenSSL. curl no longer supports Secure Transport, the macOS system TLS library; to use the system libcurl instead, configure with -DCPR_USE_SYSTEM_CURL=ON. On Windows the bundled libcurl uses the system TLS library (Schannel).

INSTALLATION

Before installing the wrapper, you have to make sure that CMake is installed on your system. It can be downloaded from here.

You can install by using CMake with FetchContent. Add the following to your CMakeLists.txt:

include(FetchContent)
FetchContent_Declare(
    ZeroBounce
    GIT_REPOSITORY https://github.com/zerobounce/zerobounce-cpp-api-wrapper.git
    GIT_TAG <DESIRED_TAG>
)
FetchContent_MakeAvailable(ZeroBounce)

This will produce the target ZeroBounce which you can link against the typical way:

target_link_libraries(your_target_name PRIVATE ZeroBounce)

If using Visual Studio Code, you can build the library using CMake and Cmake Tools extensions. After the extensions have been installed, you simply open the commands with CTRL + SHIFT + P and use CMake: Configure followed by CMake: Build.

Alternatively, you can also use the CLI commands in the root directory of your project.

LINUX
mkdir build
cmake -S . -B build -G "Unix Makefiles"
cmake --build build
WINDOWS

You have to make sure that MinGW is installed on your system. It can be installed following the steps here.

mkdir build
cmake -S . -B build -G "MinGW Makefiles"
cmake --build build

Be aware that the library may require some .dll files (found in the build directory) in order to work properly in your project.

USAGE

Include the library in your file. The examples below also print with std::cout, from <iostream>:

#include <ZeroBounce/ZeroBounce.h>
#include <iostream>

Initialize the wrapper with your api key and preferred api:

ZeroBounce::getInstance()->initialize("<YOUR_API_KEY>", ZBApiURL::Default);

Examples

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

  • ####### Check how many credits you have left on your account
ZeroBounce::getInstance()->getCredits(
    [](ZBCreditsResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### Check your API usage for a given period of time
std::tm startDate = {0};
startDate.tm_year = 118;
startDate.tm_mon = 0;
startDate.tm_mday = 1;

std::tm endDate = {0};
endDate.tm_year = 123;
endDate.tm_mon = 11;
endDate.tm_mday = 12;

ZeroBounce::getInstance()->getApiUsage(
    startDate,
    endDate,
    [](ZBGetApiUsageResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### Validate an email address
std::string email = "valid@example.com";   // The email address you want to validate
std::string ipAddress = "127.0.0.1";     // The IP Address the email signed up from (Optional)

ZeroBounce::getInstance()->validate(
    email,
    ipAddress,
    [](ZBValidateResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### Validate email batch
std::vector<ZBEmailToValidate> emails = {
    {"valid@example.com", "1.1.1.1"},
    {"invalid@example.com"}
};

ZeroBounce::getInstance()->validateBatch(
    emails,
    [](ZBValidateBatchResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### Use the Activity API endpoint to gather insights into your subscribers'overall email engagement
std::string email = "valid@example.com";    // Subscriber email address

ZeroBounce::getInstance()->getActivityData(
    email,
    [](ZBActivityDataResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### The sendfile API allows user to send a file for bulk email validation
std::string filePath = "<FILE_PATH>"; 	// The path of the csv or txt file
int emailAddressColumn = 3; 			// The index of "email" column in the file. Index starts at 1
SendFileOptions options;			// Additional options

options.returnUrl = "https://domain.com/called/after/processing/request";
options.firstNameColumn = 4;		// The index of "first name" column in the file
options.lastNameColumn = 5;		// The index of "last name" column in the file
options.genderColumn = 6;		// The index of "gender" column in the file
options.ipAddressColumn = 7;		// The index of "IP address" column in the file
options.hasHeaderRow = true;		// If this is `true` the first row is considered as table headers
options.removeDuplicate = false;	// Always sent: `true` (the default) removes duplicate emails, `false` keeps them

ZeroBounce::getInstance()->sendFile(
    filePath,
    emailAddressColumn,
    options,
    [](ZBSendFileResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### The getfile API allows users to get the validation results file for the file been submitted using sendfile API
std::string fileId = "<FILE_ID>";				// The returned file ID when calling sendfile API
std::string localDownloadPath = "<FILE_DOWNLOAD_PATH>"; 	// The location where the downloaded file will be saved

ZeroBounce::getInstance()->getFile(
    fileId,
    localDownloadPath,
    [](ZBGetFileResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);

Bulk validation uses the v2 bulk API. Optional v2 get file query parameters use getFileWithOptions / scoringGetFileWithOptions and a GetFileOptions object: set downloadType to ZBDownloadType::Phase1, ZBDownloadType::Phase2, or ZBDownloadType::Combined, and activityData to std::optional<bool> (std::nullopt to omit, true/false to send) for validation getFileWithOptions only (scoring omits activity_data). On SendFileOptions, set allowPhase2IsSet to true and allowPhase2 as needed to send allow_phase_2 for validation sendFile only (not scoringSendFile).

If the HTTP status indicates failure, the body is JSON (any JSON object, whatever its keys or content type, including HTTP 200 responses such as {"success": false, ...} or {"Message": ...}), or the download is cut short (the connection closes or times out before the whole body arrives; reported with statusCode 0), the error callback runs with a parsed message—not the get-file success callback—and no file is written. To inspect a raw body yourself, use ZeroBounce::getFileJsonIndicatesError(body); for a short message string use ZeroBounce::formatGetFileErrorMessage(body).

ZBFileStatusResponse includes filePhase2Status when the API returns it.

If CMake fails while configuring libcpr’s bundled curl (for example ZLIB::ZLIB or a missing macOS SDK include path), reconfigure with -DCPR_USE_SYSTEM_CURL=ON so the build uses the system libcurl.

  • ####### Check the status of a file uploaded via "sendFile" method
std::string fileId = "<FILE_ID>";		// The returned file ID when calling sendfile API

ZeroBounce::getInstance()->fileStatus(
    fileId,
    [](ZBFileStatusResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### Deletes the file that was submitted using sendfile API. File can be deleted only when its status is Complete
std::string fileId = "<FILE_ID>";		// The returned file ID when calling sendfile API

ZeroBounce::getInstance()->deleteFile(
    fileId,
    [](ZBDeleteFileResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### The scoringSendfile API allows user to send a file for bulk email validation
std::string filePath = "<FILE_PATH>";		// The path of the csv or txt file
int emailAddressColumn = 3; 			// The index of "email" column in the file. Index starts at 1
SendFileOptions options;			// Additional options

options.returnUrl = "https://domain.com/called/after/processing/request";
options.hasHeaderRow = true;            // If this is `true` the first row is considered as table headers


std::string scoringFileId;                      // Set by the success callback, which runs before scoringSendFile returns

ZeroBounce::getInstance()->scoringSendFile(
    filePath,
    emailAddressColumn,
    options,
    [&scoringFileId](ZBSendFileResponse response) {
        std::cout << response.toString() << std::endl;
        scoringFileId = response.fileId;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### The scoringGetFile API allows users to get the validation results file for the file been submitted using scoringSendfile API
std::string fileId = "<FILE_ID>";                       	// The returned file ID when calling scoringSendfile API
std::string localDownloadPath = "<FILE_DOWNLOAD_PATH>";  	// The location where the downloaded file will be saved

ZeroBounce::getInstance()->scoringGetFile(
    fileId,
    localDownloadPath,
    [](ZBGetFileResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### Check the status of a file uploaded via "scoringSendFile" method
std::string fileId = "<FILE_ID>";                    // The returned file ID when calling scoringSendfile API

ZeroBounce::getInstance()->scoringFileStatus(
    fileId,
    [](ZBFileStatusResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • ####### Deletes the file that was submitted using scoring scoringSendfile API. File can be deleted only when its status is Complete
std::string fileId = "<FILE_ID>";                       // The returned file ID when calling scoringSendfile API

ZeroBounce::getInstance()->scoringDeleteFile(
    fileId,
    [](ZBDeleteFileResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • Email finder allows you to identify the correct email format when you provide a name and email domain or company name

std::string domain = "example.com";         // The email domain
std::string company_name = "Example Inc";   // Or the company name
std::string first_name = "John";
std::string middle_name = "";               // Optional
std::string last_name = "Doe";

ZeroBounce::getInstance()->findEmailByDomain(
    domain,
    first_name,
    middle_name,
    last_name,
    [](ZBFindEmailResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);

ZeroBounce::getInstance()->findEmailByCompanyName(
    company_name,
    first_name,
    middle_name,
    last_name,
    [](ZBFindEmailResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);
  • Domain search allows you to identify the email domain when you provide a domain or company name

std::string domain = "example.com";         // The email domain
std::string company_name = "Example Inc";   // Or the company name

ZeroBounce::getInstance()->searchDomainByDomain(
    domain,
    [](ZBDomainSearchResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);

ZeroBounce::getInstance()->searchDomainByCompanyName(
    company_name,
    [](ZBDomainSearchResponse response) {
        std::cout << response.toString() << std::endl;
    },
    [](ZBErrorResponse errorResponse) {
        std::cout << errorResponse.toString() << std::endl;
    }
);

DEVELOPMENT

It is recommended that the development should be done on Linux.

After checking out the repo, build the library then run tests.

./build/bin/ZeroBounceTests

You should see an output like this

[==========] N tests from 4 test suites ran. (… ms total)
[  PASSED  ] N tests.

Validate options

ZeroBounce* zb = ZeroBounce::getInstance();

ZBValidateOptions options;
// domainInfo adds domainWebsiteExists and domainRegistrantCompanyName.
options.domainInfo = true;
// greylistProcessing re-runs a greylisted address instead of returning unknown.
options.greylistProcessing = true;
// callbackUrl is only allowed together with greylistProcessing = true.
options.callbackUrl = std::string("https://example.com/zerobounce-callback");

zb->validate("someone@example.com", "", options,
    [](ZBValidateResponse response) {
        // While the greylist retry is still running the API returns a message
        // instead of a result; validate again in about 30 minutes.
        std::cout << response.message << " " << response.domainWebsiteExists << std::endl;
    },
    [](ZBErrorResponse error) { std::cout << error.toString() << std::endl; }
);

Inbox Placement Tester

Lives on https://bulkapi.zerobounce.net/api/ipt and spends inbox test credits.

ZeroBounce* zb = ZeroBounce::getInstance();
// Every Inbox Placement call hands the API's JSON body to the success callback.
auto onSuccess = [](std::string json) { std::cout << json << std::endl; };
auto onError = [](ZBErrorResponse error) { std::cout << error.toString() << std::endl; };

zb->getInboxPlacementProviders(onSuccess, onError);

// testType 1 (Email) needs senderEmail; 2 is Unique ID and 3 is Auto Alias.
CreateInboxPlacementTestOptions options;
options.testType = 1;
options.senderEmail = std::string("news@example.com");
options.providers = std::vector<InboxPlacementProviderSelection>{{1, 5}};
options.webhookUrl = std::string("https://example.com/ipt-webhook");

zb->createInboxPlacementTest("October campaign", options,  // name: at most 64 characters
    [](std::string json) { std::cout << json << std::endl; },
    [](ZBErrorResponse error) { std::cout << error.toString() << std::endl; }
);

ListInboxPlacementTestsOptions filters;
filters.status = std::string("finished");
filters.page = 1;
filters.pageSize = 25;
zb->listInboxPlacementTests(filters, onSuccess, onError);

zb->getInboxPlacementTest("123", onSuccess, onError);
zb->setInboxPlacementWebhook("https://example.com/ipt-webhook", onSuccess, onError);
zb->getInboxPlacementWebhook(onSuccess, onError);
zb->deleteInboxPlacementTest("123", onSuccess, onError);

S3 and SFTP/FTP bulk

Queue a job on a file that already sits in your Amazon S3 bucket, or on your SFTP/FTP server. See the S3 and SFTP docs.

ZeroBounce* zb = ZeroBounce::getInstance();
auto ok = [](ZBSendFileResponse response) { std::cout << response.toString() << std::endl; };
auto failed = [](ZBErrorResponse error) { std::cout << error.toString() << std::endl; };

// fileName and returnUrl are required on all eight validate, score, email
// finder and domain search jobs below, S3 and SFTP/FTP alike; leaving either
// unset is rejected before a request is sent. The docs mark them optional; the
// live API rejects a job without a return URL with
// "Provided return URL is not permitted: None". listS3files and the two
// exports do not take them.

// Amazon S3. fileName is the full path, as returned by listS3files.
zb->listS3files(std::string("my-bucket"), std::string("leads"),
    [](std::vector<ZBS3ListFileEntry> files) {
        for (const auto& file : files) { std::cout << file.name << std::endl; }
    },
    failed
);

ValidateS3FileOptions validate;
validate.fileName = "lists/leads.csv";
validate.returnUrl = "https://example.com/zerobounce-done";
validate.hasHeaderRow = true;
validate.emailAddressColumn = 1;   // 1-based; set it to send it, 0 included
zb->validateS3File(validate, ok, failed);

ScoreS3FileOptions score;
score.fileName = "lists/leads.csv";
score.returnUrl = "https://example.com/zerobounce-done";
zb->scoreS3File(score, ok, failed);

BulkFileJobOptions finder;
finder.fileName = "lists/leads.csv";
finder.hasHeaderRow = true;
finder.returnUrl = "https://example.com/zerobounce-done";
zb->emailFinderS3File(finder, ok, failed);

BulkFileJobOptions domains = finder;
domains.removeDuplicates = true;
zb->domainSearchS3File(domains, ok, failed);

// export_bucket is optional: std::nullopt uses the export bucket from your
// ZeroBounce settings.
zb->exportS3File("<FILE_ID>", std::nullopt, ok, failed);
zb->exportS3File("<FILE_ID>", std::string("my-export-bucket"), ok, failed);

// SFTP/FTP. The server, path and protocol come from your ZeroBounce settings.
// The docs list fileName as optional for validateSFTPFile, but the live API
// requires it there too.
BulkFileJobOptions sftp;
sftp.fileName = "my_file.txt";
sftp.returnUrl = "https://example.com/zerobounce-done";
zb->validateSFTPFile(sftp, ok, failed);
zb->scoreSFTPFile(sftp, ok, failed);
zb->emailFinderSFTPFile(sftp, ok, failed);
zb->domainSearchSFTPFile(sftp, ok, failed);

// Note the field: this one takes export_path, not export_bucket.
// std::nullopt uses the export path from your settings.
zb->exportSFTPFile("<FILE_ID>", std::string("/exports"), ok, failed);

Per-API base URLs

The list evaluator and the Inbox Placement Tester have their own base URLs, separate from the main and bulk hosts. The three bulk hosts have setters of their own, so every bulk endpoint can be pointed at a test host. The setters strip trailing slashes, and every base URL must be https://: a call to any other URL reports url must be an https:// URL to its error callback and sends nothing.

ZeroBounce* zb = ZeroBounce::getInstance();
zb->setListEvaluatorBaseUrl("https://bulkapi.zerobounce.net/v2/listevaluator");
zb->setInboxPlacementBaseUrl("https://bulkapi.zerobounce.net/api/ipt");

// The bulk root carries the S3 and SFTP jobs, the bulk email finder and the
// bulk domain search; the other two carry bulk validation and bulk AI scoring.
zb->setBulkApiRootUrl("https://bulkapi.zerobounce.net");
zb->setBulkApiBaseUrl("https://bulkapi.zerobounce.net/v2");
zb->setBulkApiScoringBaseUrl("https://bulkapi.zerobounce.net/v2/scoring");