zero-bounce 3.0.0

Wrapper library over the ZeroBounce API v2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
# Rust ZeroBounce API


## Security

- Keep API keys on a trusted server. Do not embed them in mobile apps or browser JavaScript that untrusted users can inspect.
- Base URLs must use `https://`, including the `url_provider` fields you override. `http://` is accepted only for the hosts `127.0.0.1`, `localhost` and `[::1]` (local tests); any other `http://` URL is refused with an error before a connection is opened. Do not pass end-user-controlled hosts into those settings.
- Request URLs include `api_key` as a query parameter (ZeroBounce API contract). Do not log full request URLs or enable payload debug logging in production.

This library is a wrapper for the ZeroBounce API v2.

For more information about the API, visit https://www.zerobounce.net/docs/.

## Installation

Add the crate to `Cargo.toml`:

```toml
[dependencies]
zero-bounce = "3.0.0"
```

Requires Rust 1.88 or newer (`rust-version = "1.88"`). Upgrading from 2.x? See the
breaking changes in the [3.0.0 changelog](https://github.com/zerobounce/zerobounce-rust-api/blob/main/CHANGELOG.md#300---2026-11-11).

## How to use
This crate uses the zero-bounce API which requires an API key. Check [this guide](https://www.zerobounce.net/docs/api-dashboard#API_keys_management) to see how to grab yours.

Check the [example snippets](https://github.com/zerobounce/zerobounce-rust-api/tree/main/examples) to see how this library can be integrated in your own project.

## Configuration Options

The `ZeroBounce` client can be configured with different base URLs depending on your region or requirements.

### Default Configuration

The simplest way to create a client is using the default API URL:

```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
```

### Enum Values

You can specify a region using the `ApiBaseUrl` enum:

```rust
use zero_bounce::{ZeroBounce, ApiBaseUrl};

// USA region
let zb = ZeroBounce::with_base_url("your_api_key", ApiBaseUrl::USA)?;

// EU region
let zb = ZeroBounce::with_base_url("your_api_key", ApiBaseUrl::EU)?;

// Default (explicit)
let zb = ZeroBounce::with_base_url("your_api_key", ApiBaseUrl::Default)?;
```

### Custom URL String

You can also provide a custom base URL as a string:

```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::with_base_url("your_api_key", "https://custom-api.example.com/v2/")?;
```

`with_base_url` returns a `ZBResult`: a URL that is not `https://` is an error
(`http://` only for `127.0.0.1`, `localhost` and `[::1]`).

**Available API Base URLs:**
- `ApiBaseUrl::Default` - `https://api.zerobounce.net/v2/` (default)
- `ApiBaseUrl::USA` - `https://api-us.zerobounce.net/v2/`
- `ApiBaseUrl::EU` - `https://api-eu.zerobounce.net/v2/`

See the [config_options example](https://github.com/zerobounce/zerobounce-rust-api/tree/main/examples/config_options.rs) for a complete demonstration of all configuration options.

## Validate options

```rust
use zero_bounce::utility::structures::validate_options::ZBValidateOptions;
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("<YOUR_API_KEY>");

let options = ZBValidateOptions {
    // domain_info adds domain_website_exists and domain_registrant_company_name.
    domain_info: Some(true),
    // greylist_processing re-runs a greylisted address instead of returning unknown.
    greylist_processing: Some(true),
    // callback_url is only allowed together with greylist_processing: Some(true).
    callback_url: Some("https://example.com/zerobounce-callback".to_string()),
    ..Default::default()
};

let validation = zb.validate_email_with_options("someone@example.com", "", &options)?;

// While the greylist retry is still running the API returns a message instead
// of a result; validate again in about 30 minutes to pick it up.
println!("{:?} {:?}", validation.message, validation.domain_website_exists);
```

## Inbox Placement Tester

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

```rust
use zero_bounce::api::inbox_placement::{
    CreateInboxPlacementTestOptions, ListInboxPlacementTestsOptions,
};
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("<YOUR_API_KEY>");

let providers = zb.get_inbox_placement_providers()?;
let test_types = zb.get_inbox_placement_test_types()?;

// test_type 1 (Email) needs sender_email; 2 is Unique ID and 3 is Auto Alias.
let created = zb.create_inbox_placement_test(
    "October campaign", // required, at most 64 characters
    &CreateInboxPlacementTestOptions {
        test_type: Some(1),
        sender_email: Some("news@example.com".to_string()),
        webhook_url: Some("https://example.com/ipt-webhook".to_string()),
        ..Default::default()
    },
)?;

// Send your campaign to the seeds in `created`, then read the results.
let result = zb.get_inbox_placement_test("123")?;

let tests = zb.list_inbox_placement_tests(&ListInboxPlacementTestsOptions {
    status: Some("finished".to_string()),
    page: Some(1),
    page_size: Some(25),
    ..Default::default()
})?;

zb.set_inbox_placement_webhook("https://example.com/ipt-webhook")?;
let webhook = zb.get_inbox_placement_webhook()?;
zb.delete_inbox_placement_test("123")?;
```

## 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](https://www.zerobounce.net/docs/api-integrations/amazon-s3-bulk-api)
and [SFTP](https://www.zerobounce.net/docs/api-integrations/sftp_bulk_api) docs.

```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("<YOUR_API_KEY>");

// Amazon S3. file_name is the full path, as returned by list_s3_files.
// Every job takes file_name, has_header_row, remove_duplicates and return_url.
// The live API rejects a job with no return_url, so it is required here.
zb.validate_s3_file(
    "lists/leads.csv",
    true,                                        // has_header_row
    Some(true),                                  // remove_duplicates
    "https://example.com/zerobounce-done",       // return_url
)?;
zb.score_s3_file("lists/leads.csv", true, None, "https://example.com/zerobounce-done")?;
zb.email_finder_s3_file("lists/leads.csv", true, None, "https://example.com/zerobounce-done")?;
zb.domain_search_s3_file("lists/leads.csv", true, None, "https://example.com/zerobounce-done")?;

// Export back to S3. None uses the export bucket from your ZeroBounce settings.
zb.export_s3_file("<FILE_ID>", Some("my-export-bucket"))?;
zb.export_s3_file("<FILE_ID>", None)?;

// SFTP/FTP. The server, path and protocol come from your ZeroBounce settings.
zb.validate_sftp_file("my_file.txt", true, None, "https://example.com/zerobounce-done")?;
zb.score_sftp_file("my_file.txt", true, None, "https://example.com/zerobounce-done")?;
zb.email_finder_sftp_file("my_file.txt", true, None, "https://example.com/zerobounce-done")?;
zb.domain_search_sftp_file("my_file.txt", true, None, "https://example.com/zerobounce-done")?;

// Note the field: this one takes export_path, not export_bucket.
// None uses the export path from your settings.
zb.export_sftp_file("<FILE_ID>", Some("/exports"))?;
```

## Bulk email finder and domain search files

Run the email finder or domain search over a whole file. These four-step flows
(submit, status, download, delete) live on the bulk host *without* the `/v2`
path the other bulk APIs use. See the
[bulk email finder](https://www.zerobounce.net/docs/email-finder-api/) and
[domain search](https://www.zerobounce.net/docs/domain-search-api/) docs.

```rust
use zero_bounce::{ZBBulkResponse, ZBEmailFinderFileOptions, ZeroBounce};

let zb = ZeroBounce::new("<YOUR_API_KEY>");

// Email finder. domain_column is required; so is one of first_name_column or
// full_name_column — the API cannot guess a person from a domain alone.
let submitted = zb.send_email_finder_file(
    1,                                      // domain_column
    &ZBEmailFinderFileOptions {
        first_name_column: Some(2),
        last_name_column: Some(3),
        has_header_row: Some(true),
        ..Default::default()
    },
    "leads.csv",
    std::fs::File::open("leads.csv")?,
)?;
let file_id = submitted.file_id.unwrap_or_default();

zb.email_finder_file_status(&file_id)?;
if let ZBBulkResponse::Content(bytes) = zb.email_finder_result_fetch(&file_id)? {
    std::fs::write("results.csv", bytes)?;
}
zb.email_finder_result_delete(&file_id)?;

// Domain search. has_header_row is omitted when None, so the account default applies.
let submitted = zb.send_domain_search_file(
    1,                 // domain_column
    Some(true),        // has_header_row
    "domains.csv",
    std::fs::File::open("domains.csv")?,
)?;
let file_id = submitted.file_id.unwrap_or_default();

zb.domain_search_file_status(&file_id)?;
let results = zb.domain_search_result_fetch(&file_id)?;
zb.domain_search_result_delete(&file_id)?;
```

`email_finder_result_fetch` and `domain_search_result_fetch` follow the same
rules as `bulk_validation_result_fetch`: the file bytes come back as
`ZBBulkResponse::Content`, while a JSON body — including an HTTP 200 carrying
`{"success": false}` — is an `Err` with a short message.

## Per-API base URLs

The list evaluator and the Inbox Placement Tester have their own base URLs,
separate from the main and bulk hosts. Overrides follow the same rule as every
other base URL: `https://`, or `http://` only for `127.0.0.1`, `localhost` and `[::1]`.

```rust
use zero_bounce::ZeroBounce;

let mut zb = ZeroBounce::new("<YOUR_API_KEY>");
zb.url_provider.list_evaluator_url =
    "https://bulkapi.zerobounce.net/v2/listevaluator".to_string();
zb.url_provider.inbox_placement_url =
    "https://bulkapi.zerobounce.net/api/ipt".to_string();
```

## Email Finding Methods

### find_email_v2 (Recommended)

Find an email address using either a domain or company name. Uses the builder pattern for ergonomic API calls.

**Requirements:**
- Exactly one of `domain` or `company_name` must be provided (XOR requirement)
- `first_name` is optional. Without it the API answers with the domain's address
  formats, the same as `domain_search_v2`. Setting it to an empty string is still
  rejected.

**Builder Methods:**
- `.first_name(name: &str)` - Set the first name (optional)
- `.domain(domain: &str)` - Set the domain name
- `.company_name(company: &str)` - Set the company name
- `.middle_name(name: &str)` - Set the middle name (optional)
- `.last_name(name: &str)` - Set the last name (optional)
- `.call()` - Execute the API call

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");

// Using domain
let result = zb.find_email_v2()
    .first_name("John")
    .domain("example.com")
    .last_name("Doe")
    .call()?;

// Using company name
let result = zb.find_email_v2()
    .first_name("John")
    .company_name("Example Inc")
    .last_name("Doe")
    .call()?;

// With middle name
let result = zb.find_email_v2()
    .first_name("John")
    .domain("example.com")
    .middle_name("Middle")
    .last_name("Doe")
    .call()?;
```

**Returns:** `FindEmailResponseV2` containing:
- `email`: The found email address
- `domain`: Domain name
- `confidence`: Email confidence level (from `email_confidence` field)
- `company_name`: Company name
- `did_you_mean`: Suggested alternative
- `failure_reason`: Reason for failure if any

### find_email (Deprecated)

⚠️ **Deprecated since version 1.2.0** - Use `find_email_v2` instead.

This method is kept for backward compatibility but will be removed in a future version. The new `find_email_v2` method supports both domain and company_name parameters.

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
#[allow(deprecated)]
let result = zb.find_email("example.com", "John", "", "Doe")?;
```

## Domain Search Methods

### domain_search_v2 (Recommended)

Search for email formats using either a domain or company name. Uses the builder pattern for ergonomic API calls.

**Requirements:**
- Exactly one of `domain` or `company_name` must be provided (XOR requirement)

**Builder Methods:**
- `.domain(domain: &str)` - Set the domain name
- `.company_name(company: &str)` - Set the company name
- `.call()` - Execute the API call

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");

// Using domain
let result = zb.domain_search_v2()
    .domain("example.com")
    .call()?;

// Using company name
let result = zb.domain_search_v2()
    .company_name("Example Inc")
    .call()?;
```

**Returns:** `DomainSearchResponseV2` containing:
- `domain`: Domain name
- `company_name`: Company name
- `format`: Email format found
- `confidence`: Confidence level
- `other_domain_formats`: Alternative formats with confidence levels
- `did_you_mean`: Suggested alternative
- `failure_reason`: Reason for failure if any

### domain_search (Deprecated)

⚠️ **Deprecated since version 1.2.0** - Use `domain_search_v2` instead.

This method is kept for backward compatibility but will be removed in a future version. The new `domain_search_v2` method supports both domain and company_name parameters.

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
#[allow(deprecated)]
let result = zb.domain_search("example.com")?;
```

## Account & Usage Methods

### get_credits

Get the number of credits remaining in your ZeroBounce account.

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let credits = zb.get_credits()?;
println!("Credits remaining: {}", credits);
```

**Returns:** `i64` - The number of credits remaining in your account

### get_api_usage

Get API usage statistics for a specific date range.

**Arguments:**
- `start_date: NaiveDate` - Start date for the usage period
- `end_date: NaiveDate` - End date for the usage period

**Example:**
```rust
use zero_bounce::ZeroBounce;
use chrono::NaiveDate;

let zb = ZeroBounce::new("your_api_key");
let start = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
let end = NaiveDate::from_ymd_opt(2024, 1, 31).unwrap();
let usage = zb.get_api_usage(start, end)?;
println!("Total API calls: {}", usage.total);
```

**Returns:** `ApiUsage` containing:
- `total`: Total number of API calls in the period
- `status_valid`: Number of valid email addresses
- `status_invalid`: Number of invalid email addresses
- `status_catch_all`: Number of catch-all email addresses
- `status_do_not_mail`: Number of do-not-mail addresses
- `status_spamtrap`: Number of spamtrap addresses
- `status_unknown`: Number of unknown addresses
- `sub_status_antispam_system`: Number of antispam system responses
- `sub_status_greylisted`: Number of greylisted responses
- `sub_status_mail_server_temporary_error`: Number of temporary mail server errors
- `sub_status_forcible_disconnect`: Number of forcible disconnects
- `sub_status_mail_server_did_not_respond`: Number of non-responsive mail servers
- `sub_status_timeout_exceeded`: Number of timeout errors
- `sub_status_failed_smtp_connection`: Number of failed SMTP connections
- `sub_status_mailbox_quota_exceeded`: Number of mailbox quota exceeded errors
- `sub_status_exception_occurred`: Number of exceptions
- `sub_status_possible_trap`: Number of possible traps
- `sub_status_role_based`: Number of role-based addresses
- `sub_status_global_suppression`: Number of globally suppressed addresses
- `sub_status_mailbox_not_found`: Number of mailbox not found errors
- `sub_status_no_dns_entries`: Number of no DNS entries errors
- `sub_status_failed_syntax_check`: Number of failed syntax checks
- `sub_status_possible_typo`: Number of possible typos
- `sub_status_unroutable_ip_address`: Number of unroutable IP addresses
- `sub_status_leading_period_removed`: Number of leading periods removed
- `sub_status_does_not_accept_mail`: Number of addresses that don't accept mail
- `sub_status_alias_address`: Number of alias addresses
- `sub_status_role_based_catch_all`: Number of role-based catch-all addresses
- `sub_status_accept_all`: Number of accept-all addresses
- `sub_status_disposable`: Number of disposable addresses
- `sub_status_toxic`: Number of toxic addresses
- `sub_status_mx_forward`, `sub_status_alternate`, `sub_status_allowed`, `sub_status_blocked`, `sub_status_gold`, `sub_status_role_based_accept_all`: Counts for those sub-statuses
- `start_date`, `end_date`: The period the counts cover

The API returns only the counters that apply to your account and the period, so
every counter is 0 when the API leaves it out.

### get_api_usage_overall

Get overall API usage statistics from January 1, 2000 to the current date.

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let overall_usage = zb.get_api_usage_overall()?;
println!("Total API calls overall: {}", overall_usage.total);
```

**Returns:** `ApiUsage` - Same structure as `get_api_usage`

### get_activity_data

Get activity data for a specific email address, including when it was last seen sending emails.

**Arguments:**
- `email: &str` - The email address to check

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let activity = zb.get_activity_data("valid@example.com")?;
println!("Found: {}", activity.found);
if activity.found {
    println!("Active in the last {:?} days", activity.active_in_days);
}
```

**Returns:** `ActivityData` containing:
- `found`: Whether activity data was found for the email
- `active_in_days`: `Option<u128>`, the number of days within which the address was last seen active, as the API reports it; `None` when there is no activity data

## Email Validation Methods

### validate_email

Validate a single email address.

**Arguments:**
- `email: &str` - The email address to validate

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let validation = zb.validate_email("valid@example.com")?;
println!("Status: {}", validation.status);
println!("Sub status: {:?}", validation.sub_status);
```

**Returns:** `ZBValidation` containing:
- `address`: The email address that was validated
- `status`: Validation status (`valid`, `invalid`, `catch-all`, `unknown`, `spamtrap`, `abuse`, `do_not_mail`)
- `sub_status`: Sub-status providing more details about the validation result (`validation.status_enum()` / `validation.sub_status_enum()` give the typed `ZBValidateStatus` / `ZBValidateSubStatus`)
- `free_email`: Whether the address is on a free email provider
- `account`: Account name (if available)
- `domain`: Domain name
- `did_you_mean`: Suggested alternative email address
- `domain_age_days`: Age of the domain in days
- `active_in_days`, `active_first_seen`: Activity data (if available)
- `smtp_provider`: SMTP provider name
- `catchall_domain`: Whether the domain is catch-all (if returned)
- `mx_found`: Whether MX records were found
- `mx_record`: MX record value
- `firstname`: First name associated with the email (if available)
- `lastname`: Last name associated with the email (if available)
- `gender`: Gender associated with the email (if available)
- `country`: Country associated with the email (if available)
- `region`: Region associated with the email (if available)
- `city`: City associated with the email (if available)
- `zipcode`: Zipcode associated with the email (if available)
- `domain_website_exists`, `domain_registrant_company_name`: With the `domain_info` option
- `message`: Set instead of a result while greylist processing is still running
- `processed_at`: Timestamp when the validation was processed

### validate_email_and_ip

Validate an email address with an optional IP address for more accurate validation.

**Arguments:**
- `email: &str` - The email address to validate
- `ip_address: &str` - Optional IP address (can be empty string)

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let validation = zb.validate_email_and_ip("valid@example.com", "99.110.204.1")?;
println!("Status: {}", validation.status);
```

**Returns:** `ZBValidation` - Same structure as `validate_email`

### batch_validate

Validate multiple email addresses in a single API call. More efficient than validating emails one by one.

**Arguments:**
- `emails_and_ip_addresses: Vec<(String, String)>` - Vector of tuples containing (email, ip_address) pairs. IP address can be empty string.

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let emails_and_ips = vec![
    ("valid@example.com".to_string(), "99.110.204.1".to_string()),
    ("invalid@example.com".to_string(), "".to_string()),
];
let batch_result = zb.batch_validate(emails_and_ips)?;
println!("Email batch: {:#?}", batch_result.email_batch);
```

**Returns:** `ZBBatchValidation` containing:
- `email_batch`: Vector of `ZBValidation` results for each email address
- `errors`: Per-address errors (`error`, `email_address`). An account-level error (address `all`, such as an invalid key or no credits) is returned as `Err(ZBError::ApiError { .. })` instead

## Bulk Validation Methods

Bulk validation allows you to upload a file containing multiple email addresses for validation. The process involves submitting a file, checking its status, fetching results, and optionally deleting the file.

Bulk flows use the [v2 bulk API](https://www.zerobounce.net/docs/email-validation-api-quickstart/v2-send-file). For optional [v2 get file](https://www.zerobounce.net/docs/email-validation-api-quickstart/v2-get-file) query parameters, use `bulk_validation_result_fetch_with_options` / `ai_scoring_result_fetch_with_options` with `ZBGetFileOptions` (`download_type`, and `activity_data` for validation only). Use `zb_download_type::PHASE_1`, `PHASE_2`, or `COMBINED` for `download_type`. For validation sendfile only, chain `.set_allow_phase_2(Some(true))` or `Some(false)` on `ZBFile` to send `allow_phase_2` (omitted when `None`); AI scoring sendfile ignores this field.

On success, `bulk_validation_result_fetch` / `ai_scoring_result_fetch` return `ZBBulkResponse::Content` with the file bytes. Non-success HTTP statuses and JSON error bodies (including some HTTP 200 responses with `"success": false`) return `Err(ZBError::ApiError { status, message })` with a short message, not `Feedback`; `ZBError::status_code()` gives the HTTP status (for example 403 for a Cloudflare block, or 200 for a JSON error body). Use `get_file_json_indicates_error` / `format_get_file_error_message` from the crate root on a raw body string if you need to inspect responses yourself. `ZBFileStatus` includes optional `file_phase_2_status` when the API returns it.

### bulk_validation_file_submit

Submit a file for bulk email validation.

**Arguments:**
- `zb_file: &ZBFile` - A `ZBFile` instance containing the email addresses to validate

**Example:**
```rust
use zero_bounce::{ZeroBounce, ZBFile};

let zb = ZeroBounce::new("your_api_key");
// from_content takes the file's bytes (CSV, one address per line here).
let file_content = b"email1@example.com\nemail2@example.com\n".to_vec();
let zb_file = ZBFile::from_content(file_content)
    .set_has_header_row(false)
    .set_remove_duplicate(true);
let submit_result = zb.bulk_validation_file_submit(&zb_file)?;
println!("File ID: {:?}", submit_result.file_id);
```

**Returns:** `ZBFileFeedback` containing:
- `success`: Whether the file submission was successful
- `message`: Status message
- `file_name`: Optional name of the submitted file
- `file_id`: Optional file ID to use for status checks and result fetching

### bulk_validation_file_status_check

Check the processing status of a submitted bulk validation file.

**Arguments:**
- `file_id: &str` - The file ID returned from `bulk_validation_file_submit`

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let status = zb.bulk_validation_file_status_check("file_id_here")?;
println!("Complete percentage: {}%", status.complete_percentage);
println!("File status: {}", status.file_status);
```

**Returns:** `ZBFileStatus` containing:
- `success`: Whether the status check was successful
- `file_id`: The file ID
- `file_name`: Name of the file
- `upload_date`: Date when the file was uploaded
- `file_status`: Current status of the file
- `complete_percentage`: Percentage of processing completed
- `error_reason`: Why the file failed, when it did
- `file_phase_2_status`: Phase 2 status, when the API returns it
- `return_url`: The callback URL given at submission, if any

### bulk_validation_result_fetch

Fetch the results of a completed bulk validation file. Query parameters `api_key` and `file_id` are always sent.

**Arguments:**
- `file_id: &str` - The file ID returned from `bulk_validation_file_submit`

**Example:**
```rust
use zero_bounce::ZeroBounce;
use zero_bounce::ZBBulkResponse;

let zb = ZeroBounce::new("your_api_key");
let result = zb.bulk_validation_result_fetch("file_id_here")?;
if let ZBBulkResponse::Content(bytes) = result {
    println!("Received {} bytes", bytes.len());
}
```

**Returns:** `Ok(ZBBulkResponse::Content(bytes))` when the response is a successful file download. JSON or JSON-shaped error responses (including some HTTP 200 cases) and HTML error pages are `Err(ZBError::ApiError { .. })`, carrying the HTTP status.

### bulk_validation_result_fetch_with_options

Same as `bulk_validation_result_fetch`, plus optional v2 query parameters.

**Arguments:**
- `file_id: &str`
- `options: &ZBGetFileOptions` — set `download_type` and/or `activity_data` (`Some(true)` / `Some(false)`).

```rust
use zero_bounce::{ZeroBounce, ZBGetFileOptions, zb_download_type};

let zb = ZeroBounce::new("your_api_key");
let mut opts = ZBGetFileOptions::default();
opts.download_type = Some(zb_download_type::COMBINED.to_string());
opts.activity_data = Some(true);
let result = zb.bulk_validation_result_fetch_with_options("file_id_here", &opts)?;
```

### bulk_validation_result_delete

Delete a bulk validation result file from the ZeroBounce servers.

**Arguments:**
- `file_id: &str` - The file ID returned from `bulk_validation_file_submit`

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let delete_result = zb.bulk_validation_result_delete("file_id_here")?;
println!("Delete successful: {}", delete_result.success);
```

**Returns:** `ZBFileFeedback` containing:
- `success`: Whether the deletion was successful
- `message`: Status message

## AI Scoring Methods

AI Scoring allows you to upload a file containing email addresses to get AI-powered quality scores. The process is similar to bulk validation: submit a file, check status, fetch results, and optionally delete the file.

### ai_scoring_file_submit

Submit a file for AI scoring analysis.

**Arguments:**
- `zb_file: &ZBFile` - A `ZBFile` instance containing the email addresses to score

**Example:**
```rust
use zero_bounce::{ZeroBounce, ZBFile};

let zb = ZeroBounce::new("your_api_key");
// from_content takes the file's bytes (CSV, one address per line here).
let file_content = b"email1@example.com\nemail2@example.com\n".to_vec();
let zb_file = ZBFile::from_content(file_content)
    .set_has_header_row(false)
    .set_remove_duplicate(true);
let submit_result = zb.ai_scoring_file_submit(&zb_file)?;
println!("File ID: {:?}", submit_result.file_id);
```

**Returns:** `ZBFileFeedback` - Same structure as `bulk_validation_file_submit`

### ai_scoring_file_status_check

Check the processing status of a submitted AI scoring file.

**Arguments:**
- `file_id: &str` - The file ID returned from `ai_scoring_file_submit`

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let status = zb.ai_scoring_file_status_check("file_id_here")?;
println!("Complete percentage: {}%", status.complete_percentage);
```

**Returns:** `ZBFileStatus` - Same structure as `bulk_validation_file_status_check`

### ai_scoring_result_fetch

Fetch the results of a completed AI scoring file. Same success/error rules as `bulk_validation_result_fetch`.

**Arguments:**
- `file_id: &str` - The file ID returned from `ai_scoring_file_submit`

**Example:**
```rust
use zero_bounce::{ZeroBounce, ZBBulkResponse};

let zb = ZeroBounce::new("your_api_key");
let result = zb.ai_scoring_result_fetch("file_id_here")?;
if let ZBBulkResponse::Content(bytes) = result {
    println!("Received {} bytes", bytes.len());
}
```

### ai_scoring_result_fetch_with_options

Optional `download_type` only; `activity_data` on `ZBGetFileOptions` is not sent for scoring getfile.

```rust
use zero_bounce::{ZeroBounce, ZBGetFileOptions, zb_download_type};

let zb = ZeroBounce::new("your_api_key");
let mut opts = ZBGetFileOptions::default();
opts.download_type = Some(zb_download_type::PHASE_2.to_string());
let result = zb.ai_scoring_result_fetch_with_options("file_id_here", &opts)?;
```

### ai_scoring_result_delete

Delete an AI scoring result file from the ZeroBounce servers.

**Arguments:**
- `file_id: &str` - The file ID returned from `ai_scoring_file_submit`

**Example:**
```rust
use zero_bounce::ZeroBounce;

let zb = ZeroBounce::new("your_api_key");
let delete_result = zb.ai_scoring_result_delete("file_id_here")?;
println!("Delete successful: {}", delete_result.success);
```

**Returns:** `ZBFileFeedback` - Same structure as `bulk_validation_result_delete`

## Development

### Run tests with Docker
From the **`sdk-docs/`** folder in the SDKs monorepo:

```bash
cd sdk-docs
docker compose build rust
docker compose run --rm rust
```

### Local setup and tests
```bash
# install
sudo apt update
sudo apt install cargo rustc rustup
rustup update
rustup default stable
```

```bash
# run tests
cargo test
cargo test find_email_v2
cargo test --release

# output: every suite (unit tests, offline_api, offline_warmup, mod, doc-tests)
# ends with a line like
test result: ok. N passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
```

```bash
# run examples
# WARNING: examples use live server, will consume credits
cp .env.example .env
# Edit .env and set ZEROBOUNCE_API_KEY=your_api_key_here
cargo run --example # list of available examples
cargo run --example domain_search_v2
```

## Warmup API

The Warmup API is a separate product. It has its own host, its own team-scoped key, and its own client; your validation key will not work with it.

```rust
use zero_bounce::ZeroBounceWarmup;

let warmup = ZeroBounceWarmup::new("<YOUR_WARMUP_API_KEY>")?;

let accounts = warmup.list_sending_accounts()?;
let progress = warmup.get_progress_today()?;
let csv = warmup.download_seeds()?;            // CSV text, columns seed,provider
```

Add a from-address you run yourself, with one of the five standard engagement rules (0 Default, 1 Slow Pace, 2 Repair, 3 Boost, 4 Protect):

```rust
use zero_bounce::{OnboardingModel, ZeroBounceWarmup};

let warmup = ZeroBounceWarmup::new("<YOUR_WARMUP_API_KEY>")?;
warmup.add_sending_account(
    "sender@example.com",
    OnboardingModel::SelfManaged,
    Some(0),
    None,
    None,
    None,
)?;
```

A custom engagement rule can be changed only once every seven days; inside that window the API answers 429.

```rust
use zero_bounce::ZeroBounceWarmup;

let warmup = ZeroBounceWarmup::new("<YOUR_WARMUP_API_KEY>")?;
warmup.create_custom_engagement("sender@example.com", 20, 20, 35)?;  // reply, important, click %
```

`check_domain_dmarc` takes an **email address**, not a domain — the live API rejects a bare domain even though the docs describe one:

```rust
use zero_bounce::ZeroBounceWarmup;

let warmup = ZeroBounceWarmup::new("<YOUR_WARMUP_API_KEY>")?;
let dmarc = warmup.check_domain_dmarc("sender@example.com", None)?;
```

Every documented empty success (204, or an empty 200) comes back as `Ok(None)`. Failures are `ZBError::ApiError`, whose status is reachable through `ZBError::status_code()`. Nothing is stored by `test_smtp_configuration`, and the credentials you pass it are masked out of any error it raises.

## Live API suite

`cargo test` never touches the network: the live suite is behind the `live` cargo feature, so CI does not even compile it. It needs real keys, which come from the environment and are never written anywhere:

```bash
export ZEROBOUNCE_API_KEY=...          # validation API
export ZEROBOUNCE_WARMUP_API_KEY=...   # Warmup API
cargo test --features live --test live_api -- --nocapture
```

By default it only makes free calls: sandbox addresses, reads, and requests that are expected to fail but still prove the API accepts the payload. It checks that the credit balance did not move. Two flags opt in to more:

| Flag | What it adds |
| --- | --- |
| `ZEROBOUNCE_LIVE_SPEND=1` | billable calls (scoring, activity, email finder) and a bulk round trip that deletes its own job |
| `ZEROBOUNCE_LIVE_CHANGES=1` | reversible account changes — a test filter and a self-managed Warmup sending account — each undone in cleanup even when a test fails |

It never creates an Inbox Placement test, sets the Inbox Placement webhook, or starts ZB-managed Warmup onboarding, because the API cannot undo any of those.

Run it by hand before every release: the offline suite proves the SDK sends what we think it sends, and only the live suite proves the API accepts it.

## Publish

1. Bump `version` in `Cargo.toml`, commit, tag (`vX.Y.Z`), push tag.
2. **Actions → Publish → Run workflow** with that tag.

Registry: [zero-bounce on crates.io](https://crates.io/crates/zero-bounce)