Skip to content

Latest commit

 

History

10 Commits

Folders and files

Repository files navigation

BillionVerify for Java

Java client for the BillionVerify email verification API. It covers every operation of the API: single and batch verification, the free disposable check, file verification, credits, webhooks, domain search and the health check.

API reference: https://billionverify.com/docs

Installation

Java 17 or newer. The library is on Maven Central.

Maven

<dependency>
    <groupId>com.billionverify</groupId>
    <artifactId>billionverify-java</artifactId>
    <version>1.0.0</version>
</dependency>

Gradle

implementation 'com.billionverify:billionverify-java:1.0.0'

Quick start

import com.billionverify.sdk.BillionVerifyClient;
import com.billionverify.sdk.model.VerificationResult;

public class Main {
    public static void main(String[] args) throws Exception {
        try (var client = BillionVerifyClient.builder(System.getenv("BILLIONVERIFY_API_KEY")).build()) {
            VerificationResult result = client.verify("user@example.com");
            System.out.println(result.status());        // Status.VALID, Status.INVALID, ...
            System.out.println(result.isDeliverable()); // true or false
            System.out.println(result.creditsUsed());   // 1
        }
    }
}

The client is thread safe: create one and share it. Close it when you are done.

Configuration

var client = BillionVerifyClient.builder("your-api-key")
    .baseUrl("https://api.billionverify.com")  // default; a trailing /v1 is accepted
    .timeout(Duration.ofSeconds(30))           // connect, read and write, default 30 s
    .retries(3)                                // total attempts for 429/500/502/503, default 3
    .build();

Verify emails

// Switches you leave out are not sent, so the server default applies.
VerificationResult r = client.verify("user@example.com",
    VerifyOptions.builder().checkSmtp(true).forceRefresh(false).includeDomainReputation(true).build());

// Up to 50 addresses in one synchronous request.
BatchVerifyResponse batch = client.verifyBatch(List.of("a@example.com", "b@example.com"));
batch.totalEmails();
batch.results().forEach(row -> System.out.println(row.email() + " " + row.status()));
batch.deliverabilityBuckets().notDeliverable();

// Free lookup against the disposable-domain table.
client.checkDisposable("someone@mailinator.com").isDisposable();          // POST
client.checkDisposableViaQuery("someone@mailinator.com").isDisposable();  // GET

verifyBatch throws ValidationException for more than 50 addresses without sending a request; use a file upload for larger lists.

Verify a file

FileUploadResponse upload = client.uploadFile(new File("emails.csv"),
    FileUploadOptions.builder().emailColumn("email").preserveOriginal(true).build());
// Streams work too: client.uploadFile(inputStream, "emails.csv", null)

FileJobResponse job = client.waitForFileJobCompletion(upload.taskId(), Duration.ofMinutes(30));
job.status();                                   // "completed"
job.deliverabilityBuckets().strictDeliverable();

// Or check by hand. A timeout of 1-300 seconds makes the server hold the call until the job ends.
client.getFileJobStatus(upload.taskId(), 60);

// The result CSV; filters combine with OR.
byte[] csv = client.downloadFileResults(upload.taskId(),
    ResultFilters.builder().valid(true).catchall(true).build());

// A paused job continues with:
client.resumeJob(upload.taskId());

Result files are served from a pre-signed storage URL. The client follows that redirect itself and does not send your API key to the storage host.

Credits

client.getCredits().creditsBalance();

Webhooks

Webhook webhook = client.createWebhook("https://your-app.com/hooks/billionverify",
    List.of(WebhookEvent.FILE_COMPLETED, WebhookEvent.FILE_FAILED));
webhook.secret();   // returned only now, store it

client.listWebhooks();
client.deleteWebhook(webhook.id());

Verify every delivery before you trust it. The signature is an HMAC-SHA256 of "<timestamp>.<raw body>", sent as X-Webhook-Signature: sha256=<hex>, with the time in X-Webhook-Timestamp:

boolean genuine = WebhookSignature.verify(
    rawBody,                              // exactly as received
    request.getHeader("X-Webhook-Signature"),
    request.getHeader("X-Webhook-Timestamp"),
    System.getenv("BILLIONVERIFY_WEBHOOK_SECRET"));
// Deliveries older (or newer) than five minutes are rejected. Pass a Duration and an Instant
// to WebhookSignature.verify(...) to change that; Duration.ZERO turns the check off.

Domain search

Give a domain, get the emails published on its site, each one verified. It runs asynchronously and costs 5 credits per returned email; maxEmails (1-200) caps the bill.

DomainSearch.Created search = client.createDomainSearch("example.com", 20,
    DomainSearchOptions.builder().includeRoleBased(false).maxPages(100).build());
DomainSearch.Status done = client.waitForDomainSearch(search.searchId());
done.result().get("emails").forEach(e -> System.out.println(e.get("email").asText()));

// A CSV of domains
DomainSearch.BatchCreated batch = client.createDomainSearchBatch(new File("domains.csv"),
    DomainSearchOptions.builder().maxEmails(10).columnMap(Map.of("domain", "Company Website")).build());
client.getDomainSearchBatch(batch.batchId()).progress().processed();
client.listDomainSearchBatches(20, "completed", null).items();
byte[] csv = client.downloadDomainSearchBatchResults(batch.batchId());   // 409 until the batch has finished

Health

client.healthCheck().status();   // "ok"; no API key needed

Errors

Every error is a checked BillionVerifyException with getErrorCode(), getStatusCode() and getDetails().

Class When
ValidationException HTTP 400, or invalid arguments caught before the request
AuthenticationException HTTP 401
InsufficientCreditsException HTTP 402
NotFoundException HTTP 404
RateLimitException HTTP 429 after the retries; getRetryAfter() in seconds
TimeoutException The request or a waitFor... helper ran out of time
BillionVerifyException Anything else, including network failures (NETWORK_ERROR) and 409

Responses with status 429, 500, 502 and 503 are retried (up to retries attempts in total), waiting Retry-After seconds when the server sends it and 2^attempt seconds otherwise.

Examples

See examples: basic verification, file upload, webhooks and domain search.

Development

mvn verify

The tests use a local mock server; they never call the real API.

Releasing

The library is published to Maven Central through the Central Portal under the verified namespace com.billionverify.

  1. Set the version in pom.xml and src/main/java/com/billionverify/sdk/Version.java, update CHANGELOG.md, run mvn verify, commit.
  2. Tag and push: git tag v1.0.0 && git push origin main v1.0.0. The Release workflow checks that the tag matches the version, runs the tests and runs mvn deploy -P release. It needs the repository secrets MAVEN_USERNAME and MAVEN_PASSWORD (a Central Portal user token), GPG_PRIVATE_KEY and GPG_PASSPHRASE. It does nothing if that version is already on Maven Central.
  3. To release by hand: put the user token in a central server entry of ~/.m2/settings.xml, have the signing key in your GPG keyring, then mvn deploy -P release. The release profile signs the artifacts; central-publishing-maven-plugin uploads the bundle with its sources and Javadoc jars and publishes it.

License

MIT