zero-bounce 4.1.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
//! Client for the ZeroBounce Warmup API (<https://www.zerobounce.net/docs/warmup-api>).
//!
//! The Warmup API is separate from the email validation API: its own host, its
//! own team-scoped key, and an `API-Key` header instead of an `api_key`
//! parameter. Use [`ZeroBounceWarmup`] with a Warmup API key; [`crate::ZeroBounce`]
//! stays for the validation API key.

use std::collections::HashMap;

use chrono::NaiveDate;
use serde_json::{Map, Value};

use crate::utility::http_error::message_from_body;
use crate::utility::{ZBError, ZBResult};

const DEFAULT_BASE_URL: &str = "https://warmup-api.zerobounce.net";
const BASE_PATH: &str = "/api/v1/warmup";

/// Required by the schema but always replaced with the key's own team.
const ANY_TEAM_ID: i64 = 1;

/// How a sending account is run. `#[non_exhaustive]`, so a model added later
/// is not a breaking change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OnboardingModel {
    /// You run the mailbox yourself.
    SelfManaged,
    /// ZeroBounce provisions and runs the mailbox.
    ZbManaged,
}

impl OnboardingModel {
    fn as_str(self) -> &'static str {
        match self {
            OnboardingModel::SelfManaged => "self_managed",
            OnboardingModel::ZbManaged => "zb_managed",
        }
    }
}

/// What ZeroBounce should send on your behalf, for `zb_managed` onboarding,
/// with [`ZeroBounceWarmup::add_sending_account`].
///
/// Deprecated: it cannot carry the documented `company_website`,
/// `company_description` and `example_email`. Use [`ZbManagedEmailContent`]
/// with [`ZeroBounceWarmup::add_zb_managed_sending_account`]. The API does not
/// read `industry` or `website`: `industry` is not sent, and `website` is sent
/// as `company_website`.
#[deprecated(
    note = "use ZbManagedEmailContent with ZeroBounceWarmup::add_zb_managed_sending_account"
)]
#[derive(Debug, Clone, Default)]
pub struct EmailContent {
    /// Any of `transactional`, `newsletter`, `marketing`.
    pub types_of_emails: Vec<String>,
    /// Not read by the API, so not sent.
    pub industry: Option<String>,
    pub company_name: Option<String>,
    /// Sent as `company_website`, the field the API reads.
    pub website: Option<String>,
}

/// When ZeroBounce should send, for `zb_managed` onboarding, with
/// [`ZeroBounceWarmup::add_sending_account`].
///
/// Deprecated: it cannot carry the documented `weekdays_only` and `timezone`,
/// or a fractional `timezone_offset` such as 5.5. Use [`ZbManagedSending`] with
/// [`ZeroBounceWarmup::add_zb_managed_sending_account`]. The API does not apply
/// a daily limit, so `daily_limit` is not sent.
#[deprecated(
    note = "use ZbManagedSending with ZeroBounceWarmup::add_zb_managed_sending_account"
)]
#[derive(Debug, Clone, Default)]
pub struct ManagedSending {
    /// -11 to 14.
    pub timezone_offset: Option<i32>,
    pub warmup_start_date: Option<NaiveDate>,
    /// Not applied by the API, so not sent.
    pub daily_limit: Option<u32>,
}

/// The `email_content` of a `zb_managed` sending account: the company context
/// ZeroBounce uses to write the warmup emails. Each field is sent only when set.
///
/// `#[non_exhaustive]`, so a field added later is not a breaking change: start
/// from `ZbManagedEmailContent::default()` and set the fields you need.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct ZbManagedEmailContent {
    pub company_name: Option<String>,
    pub company_website: Option<String>,
    pub company_description: Option<String>,
    /// Any of `transactional`, `newsletter`, `marketing`. Not sent when empty.
    pub types_of_emails: Vec<String>,
    pub example_email: Option<String>,
}

/// The `managed_sending` schedule of a `zb_managed` sending account. Each field
/// is sent only when set. The API cannot read it back or change it later.
///
/// `#[non_exhaustive]`, so a field added later is not a breaking change: start
/// from `ZbManagedSending::default()` and set the fields you need.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct ZbManagedSending {
    pub weekdays_only: Option<bool>,
    /// A time zone name, such as `Europe/Bucharest`.
    pub timezone: Option<String>,
    /// Hours from UTC, -11.0 to 14.0. Fractional offsets such as 5.5 are allowed.
    pub timezone_offset: Option<f64>,
    pub warmup_start_date: Option<NaiveDate>,
}

const EMAIL_TYPES: [&str; 3] = ["transactional", "newsletter", "marketing"];

pub struct ZeroBounceWarmup {
    api_key: String,
    root: String,
    client: reqwest::blocking::Client,
}

/// Names the type and every field, with the API key shown as `***`.
impl std::fmt::Debug for ZeroBounceWarmup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ZeroBounceWarmup")
            .field("api_key", &crate::utility::redacted_key(&self.api_key))
            .field("root", &self.root)
            .field("client", &self.client)
            .finish()
    }
}

impl ZeroBounceWarmup {
    /// A client for the default Warmup host.
    pub fn new(api_key: &str) -> ZBResult<Self> {
        Self::with_base_url(api_key, DEFAULT_BASE_URL)
    }

    /// A client for a custom https base URL.
    pub fn with_base_url(api_key: &str, base_url: &str) -> ZBResult<Self> {
        if api_key.trim().is_empty() {
            return Err(ZBError::explicit("api_key is required"));
        }
        crate::utility::check_key_text(api_key)?;
        // https only, with the same loopback exception the validation client
        // makes so the offline suite can point at a local fake.
        crate::parse_request_url(base_url).map_err(|error| match error.to_string().as_str() {
            // Specific refusals keep their own fixed text.
            m if m == crate::USERINFO_MESSAGE || m == crate::URL_TEXT_MESSAGE => error,
            _ => ZBError::explicit("base_url must be an https:// URL"),
        })?;
        Ok(ZeroBounceWarmup {
            api_key: api_key.to_string(),
            root: format!("{}{BASE_PATH}", base_url.trim_end_matches('/')),
            client: crate::utility::http_client()?,
        })
    }

    // -- transport -----------------------------------------------------------

    /// Replace every form of a secret in a message with `***`.
    fn redact(&self, text: &str, secrets: &[&str]) -> String {
        let all: Vec<&str> = std::iter::once(self.api_key.as_str())
            .chain(secrets.iter().copied())
            .collect();
        crate::utility::redact_secrets(text, &all)
    }

    fn send(
        &self,
        method: &str,
        path: &str,
        query: &HashMap<&str, String>,
        body: Option<&Value>,
        secrets: &[&str],
    ) -> ZBResult<(u16, String, String)> {
        let url = crate::parse_request_url(&format!("{}{path}", self.root))?;
        let mut request = match method {
            "POST" => self.client.post(url),
            "PUT" => self.client.put(url),
            "DELETE" => self.client.delete(url),
            _ => self.client.get(url),
        }
        .header("API-Key", self.api_key.as_str())
        .header(reqwest::header::ACCEPT, "application/json")
        .query(query);

        if let Some(body) = body {
            // reqwest's json() helper needs its "json" feature, which this
            // crate does not enable, so the body and content type are set here.
            let encoded = serde_json::to_string(body)
                .map_err(|_| ZBError::explicit("Invalid parameter: request body"))?;
            request = request
                .header(reqwest::header::CONTENT_TYPE, "application/json")
                .body(encoded);
        }

        let response = request
            .send()
            .map_err(|error| ZBError::ExplicitError(self.redact(&error.to_string(), secrets)))?;
        let status = response.status().as_u16();
        // A redirect is refused before its body is read.
        if (300..400).contains(&status) {
            return Err(ZBError::api(
                status,
                crate::utility::http_error::REDIRECT_REFUSED_MESSAGE,
            ));
        }
        // reqwest's decompression is not enabled, so an encoded body would be
        // handed on as its raw compressed bytes.
        let encodings: Vec<Option<&str>> = response
            .headers()
            .get_all(reqwest::header::CONTENT_ENCODING)
            .iter()
            .map(|value| value.to_str().ok())
            .collect();
        if crate::utility::bulk_get_file::content_encoding_is_transformed(encodings) {
            return Err(ZBError::api(
                status,
                crate::utility::bulk_get_file::ENCODED_BODY_MESSAGE,
            ));
        }
        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .unwrap_or("")
            .to_string();
        // Only a successful result file may be large; an error body is read
        // up to the normal error-body cap.
        let max_bytes = if content_type.starts_with("text/csv") && status <= 299 {
            crate::utility::MAX_GETFILE_BYTES
        } else {
            crate::utility::MAX_JSON_RESPONSE_BYTES
        };
        let body = crate::utility::read_limited(
            response,
            max_bytes,
            status,
            "response body exceeds size limit",
        )
        .map_err(|error| match error {
            // Over the size cap: the server's answer, with its status.
            ZBError::ApiError { .. } => error,
            other => ZBError::ExplicitError(self.redact(&other.to_string(), secrets)),
        })?;
        let text = String::from_utf8_lossy(&body).into_owned();

        if status > 299 {
            return Err(ZBError::api(
                status,
                self.redact(&message_from_body(status, &content_type, &text), secrets),
            ));
        }
        Ok((status, content_type, text))
    }

    /// The JSON payload of a success, or `None` for the documented empty
    /// successes (204, and an empty 200).
    fn json(
        &self,
        method: &str,
        path: &str,
        query: &HashMap<&str, String>,
        body: Option<&Value>,
        secrets: &[&str],
    ) -> ZBResult<Option<Value>> {
        let (status, content_type, text) = self.send(method, path, query, body, secrets)?;
        // A body of whitespace is not empty: it is not JSON either.
        if status == 204 || text.is_empty() {
            return Ok(None);
        }
        // A text/html response is a page (a proxy or a challenge), not the
        // API's answer, even when its body happens to parse as JSON.
        if crate::utility::http_error::content_type_is_html(&content_type) {
            return Err(ZBError::api(
                status,
                self.redact(&message_from_body(status, &content_type, &text), secrets),
            ));
        }
        match serde_json::from_str::<Value>(&text) {
            Ok(value) => Ok(Some(value)),
            Err(_) => Err(ZBError::api(
                status,
                self.redact(&message_from_body(status, &content_type, &text), secrets),
            )),
        }
    }

    fn get(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<Option<Value>> {
        self.json("GET", path, query, None, &[])
    }

    fn write(&self, method: &str, path: &str, body: Value) -> ZBResult<Option<Value>> {
        self.json(method, path, &HashMap::new(), Some(&body), &[])
    }

    /// A CSV download, returned as text.
    fn csv(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<String> {
        let (status, content_type, text) = self.send("GET", path, query, None, &[])?;
        // Not a CSV: an empty body (U+FEFF byte order marks are not content,
        // and `trim` does not remove them), JSON (by content type, or a body
        // that starts with `{` or `[` whether or not it parses) or an HTML
        // page (by content type or body). A plain CSV, with or without a
        // leading BOM, is returned as received.
        let sniffed = crate::utility::bulk_get_file::strip_leading_boms(&text);
        if sniffed.trim().is_empty()
            || crate::utility::bulk_get_file::should_treat_get_file_body_as_error(
                sniffed,
                &content_type,
            )
            || crate::utility::http_error::content_type_is_html(&content_type)
            || crate::utility::http_error::body_looks_like_html(sniffed)
        {
            return Err(ZBError::api(
                status,
                self.redact(&message_from_body(status, &content_type, sniffed), &[]),
            ));
        }
        Ok(text)
    }

    // -- argument checks -----------------------------------------------------

    fn required<'a>(value: &'a str, name: &str) -> ZBResult<&'a str> {
        if value.trim().is_empty() {
            return Err(ZBError::ExplicitError(format!("{name} is required")));
        }
        Ok(value)
    }

    fn in_range(value: i64, low: i64, high: i64, name: &str) -> ZBResult<i64> {
        if !(low..=high).contains(&value) {
            return Err(ZBError::ExplicitError(format!(
                "{name} must be {low} to {high}"
            )));
        }
        Ok(value)
    }

    fn engagement_body(
        c_from: &str,
        reply_pct: i64,
        important_pct: i64,
        click_pct: i64,
    ) -> ZBResult<Value> {
        Self::required(c_from, "c_from")?;
        Self::in_range(reply_pct, 5, 45, "reply_pct")?;
        Self::in_range(important_pct, 5, 40, "important_pct")?;
        Self::in_range(click_pct, 0, 70, "click_pct")?;
        if (click_pct as f64) > important_pct as f64 * 1.75 {
            return Err(ZBError::explicit(
                "click_pct must be at most important_pct x 1.75",
            ));
        }
        Ok(Value::Object(Map::from_iter([
            ("c_from".into(), Value::String(c_from.to_string())),
            ("reply_pct".into(), Value::from(reply_pct)),
            ("important_pct".into(), Value::from(important_pct)),
            ("click_pct".into(), Value::from(click_pct)),
        ])))
    }

    // -- sending accounts ----------------------------------------------------

    /// Every sending account of the key's team. `GET /sending-accounts`
    pub fn list_sending_accounts(&self) -> ZBResult<Option<Value>> {
        self.get("/sending-accounts", &HashMap::new())
    }

    /// One sending account. `GET /sending-account`
    pub fn get_sending_account(&self, from_address: &str) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        self.get(
            "/sending-account",
            &HashMap::from([("from_address", from_address.to_string())]),
        )
    }

    /// Add a from-address to warmup. `POST /sending-accounts`
    ///
    /// `SelfManaged` runs your own mailbox and needs `engagement_rule_id` 0-4.
    /// `ZbManaged` has ZeroBounce provision it and takes `email_content` and
    /// `managed_sending`; a 200 means accepted, and the mailbox is provisioned
    /// afterwards. For `zb_managed`, prefer
    /// [`add_zb_managed_sending_account`](Self::add_zb_managed_sending_account),
    /// which takes every documented field.
    #[allow(deprecated)]
    pub fn add_sending_account(
        &self,
        from_address: &str,
        onboarding_model: OnboardingModel,
        engagement_rule_id: Option<i64>,
        ignore_conflict: Option<bool>,
        email_content: Option<&EmailContent>,
        managed_sending: Option<&ManagedSending>,
    ) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        let mut body = Map::from_iter([
            ("from_address".into(), Value::String(from_address.into())),
            (
                "onboarding_model".into(),
                Value::String(onboarding_model.as_str().into()),
            ),
        ]);

        if onboarding_model == OnboardingModel::SelfManaged {
            let Some(rule) = engagement_rule_id else {
                return Err(ZBError::explicit(
                    "engagement_rule_id is required for self_managed",
                ));
            };
            body.insert(
                "engagement_rule_id".into(),
                Value::from(Self::in_range(rule, 0, 4, "engagement_rule_id")?),
            );
            if email_content.is_some() || managed_sending.is_some() {
                return Err(ZBError::explicit(
                    "email_content and managed_sending are for zb_managed",
                ));
            }
        }
        if let Some(flag) = ignore_conflict {
            body.insert("ignore_conflict".into(), Value::Bool(flag));
        }
        // The 3.0.0 structs, mapped onto the documented fields: `website` is
        // the API's `company_website`; `industry` and `daily_limit` are not
        // read by the API and are dropped. A whole-hour offset stays an integer.
        #[allow(deprecated)]
        if let Some(content) = email_content {
            let documented = ZbManagedEmailContent {
                company_name: content.company_name.clone(),
                company_website: content.website.clone(),
                types_of_emails: content.types_of_emails.clone(),
                ..ZbManagedEmailContent::default()
            };
            body.insert("email_content".into(), Self::email_content_body(&documented)?);
        }
        #[allow(deprecated)]
        if let Some(sending) = managed_sending {
            let documented = ZbManagedSending {
                warmup_start_date: sending.warmup_start_date,
                ..ZbManagedSending::default()
            };
            let mut object = Self::managed_sending_body(&documented)?;
            if let Some(offset) = sending.timezone_offset {
                Self::in_range(i64::from(offset), -11, 14, "timezone_offset")?;
                if let Value::Object(map) = &mut object {
                    map.insert("timezone_offset".into(), Value::from(offset));
                }
            }
            body.insert("managed_sending".into(), object);
        }
        self.write("POST", "/sending-accounts", Value::Object(body))
    }

    /// Add a from-address that ZeroBounce provisions and sends from
    /// (`zb_managed` onboarding). `POST /sending-accounts`
    ///
    /// `email_content` and `managed_sending` are optional and send only the
    /// fields that are set. A 200 means the request was accepted; the mailbox
    /// is provisioned afterwards.
    pub fn add_zb_managed_sending_account(
        &self,
        from_address: &str,
        ignore_conflict: Option<bool>,
        email_content: Option<&ZbManagedEmailContent>,
        managed_sending: Option<&ZbManagedSending>,
    ) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        let mut body = Map::from_iter([
            ("from_address".into(), Value::String(from_address.into())),
            (
                "onboarding_model".into(),
                Value::String(OnboardingModel::ZbManaged.as_str().into()),
            ),
        ]);
        if let Some(flag) = ignore_conflict {
            body.insert("ignore_conflict".into(), Value::Bool(flag));
        }
        if let Some(content) = email_content {
            body.insert("email_content".into(), Self::email_content_body(content)?);
        }
        if let Some(sending) = managed_sending {
            body.insert("managed_sending".into(), Self::managed_sending_body(sending)?);
        }
        self.write("POST", "/sending-accounts", Value::Object(body))
    }

    fn email_content_body(content: &ZbManagedEmailContent) -> ZBResult<Value> {
        let mut object = Map::new();
        for (key, value) in [
            ("company_name", &content.company_name),
            ("company_website", &content.company_website),
            ("company_description", &content.company_description),
        ] {
            if let Some(value) = value {
                object.insert(key.into(), Value::String(value.clone()));
            }
        }
        if !content.types_of_emails.is_empty() {
            for kind in &content.types_of_emails {
                if !EMAIL_TYPES.contains(&kind.as_str()) {
                    return Err(ZBError::explicit(
                        "types_of_emails must be transactional, newsletter and/or marketing",
                    ));
                }
            }
            object.insert(
                "types_of_emails".into(),
                Value::Array(
                    content
                        .types_of_emails
                        .iter()
                        .map(|kind| Value::String(kind.clone()))
                        .collect(),
                ),
            );
        }
        if let Some(example) = &content.example_email {
            object.insert("example_email".into(), Value::String(example.clone()));
        }
        Ok(Value::Object(object))
    }

    fn managed_sending_body(sending: &ZbManagedSending) -> ZBResult<Value> {
        let mut object = Map::new();
        if let Some(flag) = sending.weekdays_only {
            object.insert("weekdays_only".into(), Value::Bool(flag));
        }
        if let Some(timezone) = &sending.timezone {
            object.insert("timezone".into(), Value::String(timezone.clone()));
        }
        if let Some(offset) = sending.timezone_offset {
            // NaN and the infinities fail the range check too.
            if !(-11.0..=14.0).contains(&offset) {
                return Err(ZBError::explicit("timezone_offset must be -11.0 to 14.0"));
            }
            object.insert("timezone_offset".into(), Value::from(offset));
        }
        if let Some(date) = sending.warmup_start_date {
            object.insert(
                "warmup_start_date".into(),
                Value::String(date.format("%F").to_string()),
            );
        }
        Ok(Value::Object(object))
    }

    /// Change an account's engagement rule, status and auto-enable flag.
    /// `PUT /sending-accounts`. `status_id` is 0 to 8 (4 Paused, 5 Disabled).
    pub fn update_sending_account(
        &self,
        from_address: &str,
        engagement_rule_id: i64,
        status_id: i64,
        auto_enable: bool,
    ) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        let body = Value::Object(Map::from_iter([
            ("team_id".into(), Value::from(ANY_TEAM_ID)),
            ("from_address".into(), Value::String(from_address.into())),
            (
                "engagement_rule_id".into(),
                Value::from(Self::in_range(engagement_rule_id, 0, 4, "engagement_rule_id")?),
            ),
            (
                "status_id".into(),
                Value::from(Self::in_range(status_id, 0, 8, "status_id")?),
            ),
            ("auto_enable".into(), Value::Bool(auto_enable)),
        ]));
        self.write("PUT", "/sending-accounts", body)
    }

    /// Remove a sending account. `DELETE /sending-accounts`. Destructive and final.
    pub fn delete_sending_account(&self, from_address: &str) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        self.json(
            "DELETE",
            "/sending-accounts",
            &HashMap::from([("from_address", from_address.to_string())]),
            None,
            &[],
        )
    }

    /// Move an account and its history to a new from-address.
    /// `PUT /smtp-credentials` — despite the path, no SMTP credentials are stored.
    pub fn change_from_address(
        &self,
        old_from_address: &str,
        new_from_address: &str,
    ) -> ZBResult<Option<Value>> {
        Self::required(old_from_address, "old_from_address")?;
        Self::required(new_from_address, "new_from_address")?;
        let body = Value::Object(Map::from_iter([
            ("team_id".into(), Value::from(ANY_TEAM_ID)),
            (
                "old_from_address".into(),
                Value::String(old_from_address.into()),
            ),
            (
                "new_from_address".into(),
                Value::String(new_from_address.into()),
            ),
        ]));
        self.write("PUT", "/smtp-credentials", body)
    }

    /// Registered from-addresses. `GET /from-addresses`
    ///
    /// `search_from` takes letters, digits and `. - _ @ +` only. `offset` and
    /// `limit` go on the wire as strings.
    pub fn list_from_addresses(
        &self,
        search_from: Option<&str>,
        offset: Option<u32>,
        limit: Option<u32>,
    ) -> ZBResult<Option<Value>> {
        let mut query = HashMap::new();
        if let Some(search) = search_from {
            if !search
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || ".-_@+".contains(c))
            {
                return Err(ZBError::explicit(
                    "search_from takes letters, digits and . - _ @ + only",
                ));
            }
            query.insert("search_from", search.to_string());
        }
        if let Some(offset) = offset {
            query.insert("offset", offset.to_string());
        }
        if let Some(limit) = limit {
            query.insert("limit", limit.to_string());
        }
        self.get("/from-addresses", &query)
    }

    // -- engagement rules ----------------------------------------------------

    /// -1 Custom, 0 Default, 1 Slow Pace, 2 Repair, 3 Boost, 4 Protect.
    pub fn get_engagement_rules(&self) -> ZBResult<Option<Value>> {
        self.get("/engagement-rules", &HashMap::new())
    }

    /// Set a standard rule (0 to 4) on an address. `PUT /engagement-rule`
    pub fn set_engagement_rule(&self, c_from: &str, rule_id: i64) -> ZBResult<Option<Value>> {
        Self::required(c_from, "c_from")?;
        let body = Value::Object(Map::from_iter([(
            "rule_id".to_string(),
            Value::from(Self::in_range(rule_id, 0, 4, "rule_id")?),
        )]));
        self.json(
            "PUT",
            "/engagement-rule",
            &HashMap::from([("c_from", c_from.to_string())]),
            Some(&body),
            &[],
        )
    }

    /// An address's custom rule, with `can_update` and `remaining_seconds`.
    pub fn get_custom_engagement(&self, c_from: &str) -> ZBResult<Option<Value>> {
        Self::required(c_from, "c_from")?;
        let path = format!(
            "/custom-engagement/{}",
            crate::utility::encode_path_segment(c_from.trim())
        );
        if c_from.trim() == "." || c_from.trim() == ".." {
            return Err(ZBError::explicit("c_from is invalid"));
        }
        self.get(&path, &HashMap::new())
    }

    /// Create a custom rule. Starts a 7 day cooldown on updates.
    pub fn create_custom_engagement(
        &self,
        c_from: &str,
        reply_pct: i64,
        important_pct: i64,
        click_pct: i64,
    ) -> ZBResult<Option<Value>> {
        let body = Self::engagement_body(c_from, reply_pct, important_pct, click_pct)?;
        self.write("POST", "/custom-engagement", body)
    }

    /// Update a custom rule. During the 7 day cooldown the API answers 429.
    pub fn update_custom_engagement(
        &self,
        c_from: &str,
        reply_pct: i64,
        important_pct: i64,
        click_pct: i64,
    ) -> ZBResult<Option<Value>> {
        let body = Self::engagement_body(c_from, reply_pct, important_pct, click_pct)?;
        self.write("PUT", "/custom-engagement", body)
    }

    /// Delete a custom rule and fall back to standard rule 1-4.
    pub fn delete_custom_engagement(
        &self,
        c_from: &str,
        engagement_rule_id: i64,
    ) -> ZBResult<Option<Value>> {
        Self::required(c_from, "c_from")?;
        let body = Value::Object(Map::from_iter([
            ("c_from".to_string(), Value::String(c_from.into())),
            (
                "engagement_rule_id".to_string(),
                Value::from(Self::in_range(engagement_rule_id, 1, 4, "engagement_rule_id")?),
            ),
        ]));
        self.write("DELETE", "/custom-engagement", body)
    }

    // -- statistics, seeds and utilities -------------------------------------

    /// The seed list. `GET /seeds`
    pub fn get_seeds(&self) -> ZBResult<Option<Value>> {
        self.get("/seeds", &HashMap::new())
    }

    /// The seed list as CSV (columns `seed,provider`). `GET /seeds/download`
    pub fn download_seeds(&self) -> ZBResult<String> {
        self.csv("/seeds/download", &HashMap::new())
    }

    /// Number of seeds. `GET /seed-count`
    pub fn get_seed_count(&self) -> ZBResult<Option<Value>> {
        self.get("/seed-count", &HashMap::new())
    }

    /// Today's warmup progress. `GET /progress-today`
    pub fn get_progress_today(&self) -> ZBResult<Option<Value>> {
        self.get("/progress-today", &HashMap::new())
    }

    /// Messages sent today. `GET /sent-today`
    pub fn get_sent_today(&self) -> ZBResult<Option<Value>> {
        self.get("/sent-today", &HashMap::new())
    }

    /// Current daily volume. `GET /emails-per-day`
    pub fn get_emails_per_day(&self) -> ZBResult<Option<Value>> {
        self.get("/emails-per-day", &HashMap::new())
    }

    /// Statistics for an address. An address with no history returns zeros.
    pub fn get_statistics(&self, from_address: &str) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        self.get(
            "/statistics",
            &HashMap::from([("from_address", from_address.to_string())]),
        )
    }

    /// Daily statistics between two dates, inclusive. `GET /statistics-per-day`
    pub fn get_statistics_per_day(
        &self,
        from_address: &str,
        start_date: NaiveDate,
        end_date: NaiveDate,
    ) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        if start_date > end_date {
            return Err(ZBError::explicit("start_date is later than end_date"));
        }
        self.get(
            "/statistics-per-day",
            &HashMap::from([
                ("from_address", from_address.to_string()),
                ("start_date", start_date.format("%F").to_string()),
                ("end_date", end_date.format("%F").to_string()),
            ]),
        )
    }

    /// Detailed statistics for an address. `GET /statistics-detailed`
    pub fn get_statistics_detailed(&self, c_from: &str) -> ZBResult<Option<Value>> {
        Self::required(c_from, "c_from")?;
        self.get(
            "/statistics-detailed",
            &HashMap::from([("c_from", c_from.to_string())]),
        )
    }

    /// An address's statistics as CSV. `GET /statistics/download`
    pub fn download_statistics(&self, c_from: &str) -> ZBResult<String> {
        Self::required(c_from, "c_from")?;
        self.csv(
            "/statistics/download",
            &HashMap::from([("c_from", c_from.to_string())]),
        )
    }

    /// Statistics for one from-address. `GET /from-address-statistics`
    pub fn get_from_address_statistics(&self, from_address: &str) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        self.get(
            "/from-address-statistics",
            &HashMap::from([("from_address", from_address.to_string())]),
        )
    }

    /// SPF, DKIM and DMARC status of a from-address's domain.
    /// `GET /check-domain-dmarc`
    ///
    /// LIVE: pass an **email address**. The live API answers "Please provide a
    /// valid email address" for a bare domain, although the docs describe one.
    pub fn check_domain_dmarc(
        &self,
        from_address: &str,
        dkim_selector: Option<&str>,
    ) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        if !from_address.contains('@') {
            return Err(ZBError::explicit(
                "from_address must be an email address, e.g. sender@example.com",
            ));
        }
        let mut query = HashMap::from([("from_address", from_address.to_string())]);
        if let Some(selector) = dkim_selector {
            Self::required(selector, "dkim_selector")?;
            query.insert("dkim_selector", selector.to_string());
        }
        self.get("/check-domain-dmarc", &query)
    }

    /// Check that SMTP credentials connect and hand off a message.
    /// `POST /test-smtp-configuration`
    ///
    /// Nothing is stored, and the test message goes to a ZeroBounce test
    /// recipient, not `from_address`.
    ///
    /// LIVE: the API answers any failed SMTP login with HTTP 500. That is an
    /// API bug. The username and password are masked in every error from here.
    pub fn test_smtp_configuration(
        &self,
        from_address: &str,
        username: &str,
        password: &str,
        server: &str,
        port: u16,
    ) -> ZBResult<Option<Value>> {
        Self::required(from_address, "from_address")?;
        Self::required(username, "username")?;
        Self::required(password, "password")?;
        Self::required(server, "server")?;
        if port == 0 {
            return Err(ZBError::explicit("port must be 1 to 65535"));
        }
        let body = Value::Object(Map::from_iter([
            ("from_address".to_string(), Value::String(from_address.into())),
            ("username".to_string(), Value::String(username.into())),
            ("password".to_string(), Value::String(password.into())),
            ("server".to_string(), Value::String(server.into())),
            ("port".to_string(), Value::from(port)),
        ]));
        self.json(
            "POST",
            "/test-smtp-configuration",
            &HashMap::new(),
            Some(&body),
            &[password, username],
        )
    }
}