Skip to main content

zero_bounce/
warmup.rs

1//! Client for the ZeroBounce Warmup API (<https://www.zerobounce.net/docs/warmup-api>).
2//!
3//! The Warmup API is separate from the email validation API: its own host, its
4//! own team-scoped key, and an `API-Key` header instead of an `api_key`
5//! parameter. Use [`ZeroBounceWarmup`] with a Warmup API key; [`crate::ZeroBounce`]
6//! stays for the validation API key.
7
8use std::collections::HashMap;
9
10use chrono::NaiveDate;
11use serde_json::{Map, Value};
12
13use crate::utility::http_error::message_from_body;
14use crate::utility::{ZBError, ZBResult};
15
16const DEFAULT_BASE_URL: &str = "https://warmup-api.zerobounce.net";
17const BASE_PATH: &str = "/api/v1/warmup";
18
19/// Required by the schema but always replaced with the key's own team.
20const ANY_TEAM_ID: i64 = 1;
21
22/// How a sending account is run. `#[non_exhaustive]`, so a model added later
23/// is not a breaking change.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum OnboardingModel {
27    /// You run the mailbox yourself.
28    SelfManaged,
29    /// ZeroBounce provisions and runs the mailbox.
30    ZbManaged,
31}
32
33impl OnboardingModel {
34    fn as_str(self) -> &'static str {
35        match self {
36            OnboardingModel::SelfManaged => "self_managed",
37            OnboardingModel::ZbManaged => "zb_managed",
38        }
39    }
40}
41
42/// What ZeroBounce should send on your behalf, for `zb_managed` onboarding,
43/// with [`ZeroBounceWarmup::add_sending_account`].
44///
45/// Deprecated: it cannot carry the documented `company_website`,
46/// `company_description` and `example_email`. Use [`ZbManagedEmailContent`]
47/// with [`ZeroBounceWarmup::add_zb_managed_sending_account`]. The API does not
48/// read `industry` or `website`: `industry` is not sent, and `website` is sent
49/// as `company_website`.
50#[deprecated(
51    note = "use ZbManagedEmailContent with ZeroBounceWarmup::add_zb_managed_sending_account"
52)]
53#[derive(Debug, Clone, Default)]
54pub struct EmailContent {
55    /// Any of `transactional`, `newsletter`, `marketing`.
56    pub types_of_emails: Vec<String>,
57    /// Not read by the API, so not sent.
58    pub industry: Option<String>,
59    pub company_name: Option<String>,
60    /// Sent as `company_website`, the field the API reads.
61    pub website: Option<String>,
62}
63
64/// When ZeroBounce should send, for `zb_managed` onboarding, with
65/// [`ZeroBounceWarmup::add_sending_account`].
66///
67/// Deprecated: it cannot carry the documented `weekdays_only` and `timezone`,
68/// or a fractional `timezone_offset` such as 5.5. Use [`ZbManagedSending`] with
69/// [`ZeroBounceWarmup::add_zb_managed_sending_account`]. The API does not apply
70/// a daily limit, so `daily_limit` is not sent.
71#[deprecated(
72    note = "use ZbManagedSending with ZeroBounceWarmup::add_zb_managed_sending_account"
73)]
74#[derive(Debug, Clone, Default)]
75pub struct ManagedSending {
76    /// -11 to 14.
77    pub timezone_offset: Option<i32>,
78    pub warmup_start_date: Option<NaiveDate>,
79    /// Not applied by the API, so not sent.
80    pub daily_limit: Option<u32>,
81}
82
83/// The `email_content` of a `zb_managed` sending account: the company context
84/// ZeroBounce uses to write the warmup emails. Each field is sent only when set.
85///
86/// `#[non_exhaustive]`, so a field added later is not a breaking change: start
87/// from `ZbManagedEmailContent::default()` and set the fields you need.
88#[derive(Debug, Clone, Default, PartialEq)]
89#[non_exhaustive]
90pub struct ZbManagedEmailContent {
91    pub company_name: Option<String>,
92    pub company_website: Option<String>,
93    pub company_description: Option<String>,
94    /// Any of `transactional`, `newsletter`, `marketing`. Not sent when empty.
95    pub types_of_emails: Vec<String>,
96    pub example_email: Option<String>,
97}
98
99/// The `managed_sending` schedule of a `zb_managed` sending account. Each field
100/// is sent only when set. The API cannot read it back or change it later.
101///
102/// `#[non_exhaustive]`, so a field added later is not a breaking change: start
103/// from `ZbManagedSending::default()` and set the fields you need.
104#[derive(Debug, Clone, Default, PartialEq)]
105#[non_exhaustive]
106pub struct ZbManagedSending {
107    pub weekdays_only: Option<bool>,
108    /// A time zone name, such as `Europe/Bucharest`.
109    pub timezone: Option<String>,
110    /// Hours from UTC, -11.0 to 14.0. Fractional offsets such as 5.5 are allowed.
111    pub timezone_offset: Option<f64>,
112    pub warmup_start_date: Option<NaiveDate>,
113}
114
115const EMAIL_TYPES: [&str; 3] = ["transactional", "newsletter", "marketing"];
116
117pub struct ZeroBounceWarmup {
118    api_key: String,
119    root: String,
120    client: reqwest::blocking::Client,
121}
122
123/// Names the type and every field, with the API key shown as `***`.
124impl std::fmt::Debug for ZeroBounceWarmup {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.debug_struct("ZeroBounceWarmup")
127            .field("api_key", &crate::utility::redacted_key(&self.api_key))
128            .field("root", &self.root)
129            .field("client", &self.client)
130            .finish()
131    }
132}
133
134impl ZeroBounceWarmup {
135    /// A client for the default Warmup host.
136    pub fn new(api_key: &str) -> ZBResult<Self> {
137        Self::with_base_url(api_key, DEFAULT_BASE_URL)
138    }
139
140    /// A client for a custom https base URL.
141    pub fn with_base_url(api_key: &str, base_url: &str) -> ZBResult<Self> {
142        if api_key.trim().is_empty() {
143            return Err(ZBError::explicit("api_key is required"));
144        }
145        crate::utility::check_key_text(api_key)?;
146        // https only, with the same loopback exception the validation client
147        // makes so the offline suite can point at a local fake.
148        crate::parse_request_url(base_url).map_err(|error| match error.to_string().as_str() {
149            // Specific refusals keep their own fixed text.
150            m if m == crate::USERINFO_MESSAGE || m == crate::URL_TEXT_MESSAGE => error,
151            _ => ZBError::explicit("base_url must be an https:// URL"),
152        })?;
153        Ok(ZeroBounceWarmup {
154            api_key: api_key.to_string(),
155            root: format!("{}{BASE_PATH}", base_url.trim_end_matches('/')),
156            client: crate::utility::http_client()?,
157        })
158    }
159
160    // -- transport -----------------------------------------------------------
161
162    /// Replace every form of a secret in a message with `***`.
163    fn redact(&self, text: &str, secrets: &[&str]) -> String {
164        let all: Vec<&str> = std::iter::once(self.api_key.as_str())
165            .chain(secrets.iter().copied())
166            .collect();
167        crate::utility::redact_secrets(text, &all)
168    }
169
170    fn send(
171        &self,
172        method: &str,
173        path: &str,
174        query: &HashMap<&str, String>,
175        body: Option<&Value>,
176        secrets: &[&str],
177    ) -> ZBResult<(u16, String, String)> {
178        let url = crate::parse_request_url(&format!("{}{path}", self.root))?;
179        let mut request = match method {
180            "POST" => self.client.post(url),
181            "PUT" => self.client.put(url),
182            "DELETE" => self.client.delete(url),
183            _ => self.client.get(url),
184        }
185        .header("API-Key", self.api_key.as_str())
186        .header(reqwest::header::ACCEPT, "application/json")
187        .query(query);
188
189        if let Some(body) = body {
190            // reqwest's json() helper needs its "json" feature, which this
191            // crate does not enable, so the body and content type are set here.
192            let encoded = serde_json::to_string(body)
193                .map_err(|_| ZBError::explicit("Invalid parameter: request body"))?;
194            request = request
195                .header(reqwest::header::CONTENT_TYPE, "application/json")
196                .body(encoded);
197        }
198
199        let response = request
200            .send()
201            .map_err(|error| ZBError::ExplicitError(self.redact(&error.to_string(), secrets)))?;
202        let status = response.status().as_u16();
203        // A redirect is refused before its body is read.
204        if (300..400).contains(&status) {
205            return Err(ZBError::api(
206                status,
207                crate::utility::http_error::REDIRECT_REFUSED_MESSAGE,
208            ));
209        }
210        // reqwest's decompression is not enabled, so an encoded body would be
211        // handed on as its raw compressed bytes.
212        let encodings: Vec<Option<&str>> = response
213            .headers()
214            .get_all(reqwest::header::CONTENT_ENCODING)
215            .iter()
216            .map(|value| value.to_str().ok())
217            .collect();
218        if crate::utility::bulk_get_file::content_encoding_is_transformed(encodings) {
219            return Err(ZBError::api(
220                status,
221                crate::utility::bulk_get_file::ENCODED_BODY_MESSAGE,
222            ));
223        }
224        let content_type = response
225            .headers()
226            .get(reqwest::header::CONTENT_TYPE)
227            .and_then(|value| value.to_str().ok())
228            .unwrap_or("")
229            .to_string();
230        // Only a successful result file may be large; an error body is read
231        // up to the normal error-body cap.
232        let max_bytes = if content_type.starts_with("text/csv") && status <= 299 {
233            crate::utility::MAX_GETFILE_BYTES
234        } else {
235            crate::utility::MAX_JSON_RESPONSE_BYTES
236        };
237        let body = crate::utility::read_limited(
238            response,
239            max_bytes,
240            status,
241            "response body exceeds size limit",
242        )
243        .map_err(|error| match error {
244            // Over the size cap: the server's answer, with its status.
245            ZBError::ApiError { .. } => error,
246            other => ZBError::ExplicitError(self.redact(&other.to_string(), secrets)),
247        })?;
248        let text = String::from_utf8_lossy(&body).into_owned();
249
250        if status > 299 {
251            return Err(ZBError::api(
252                status,
253                self.redact(&message_from_body(status, &content_type, &text), secrets),
254            ));
255        }
256        Ok((status, content_type, text))
257    }
258
259    /// The JSON payload of a success, or `None` for the documented empty
260    /// successes (204, and an empty 200).
261    fn json(
262        &self,
263        method: &str,
264        path: &str,
265        query: &HashMap<&str, String>,
266        body: Option<&Value>,
267        secrets: &[&str],
268    ) -> ZBResult<Option<Value>> {
269        let (status, content_type, text) = self.send(method, path, query, body, secrets)?;
270        // A body of whitespace is not empty: it is not JSON either.
271        if status == 204 || text.is_empty() {
272            return Ok(None);
273        }
274        // A text/html response is a page (a proxy or a challenge), not the
275        // API's answer, even when its body happens to parse as JSON.
276        if crate::utility::http_error::content_type_is_html(&content_type) {
277            return Err(ZBError::api(
278                status,
279                self.redact(&message_from_body(status, &content_type, &text), secrets),
280            ));
281        }
282        match serde_json::from_str::<Value>(&text) {
283            Ok(value) => Ok(Some(value)),
284            Err(_) => Err(ZBError::api(
285                status,
286                self.redact(&message_from_body(status, &content_type, &text), secrets),
287            )),
288        }
289    }
290
291    fn get(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<Option<Value>> {
292        self.json("GET", path, query, None, &[])
293    }
294
295    fn write(&self, method: &str, path: &str, body: Value) -> ZBResult<Option<Value>> {
296        self.json(method, path, &HashMap::new(), Some(&body), &[])
297    }
298
299    /// A CSV download, returned as text.
300    fn csv(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<String> {
301        let (status, content_type, text) = self.send("GET", path, query, None, &[])?;
302        // Not a CSV: an empty body (U+FEFF byte order marks are not content,
303        // and `trim` does not remove them), JSON (by content type, or a body
304        // that starts with `{` or `[` whether or not it parses) or an HTML
305        // page (by content type or body). A plain CSV, with or without a
306        // leading BOM, is returned as received.
307        let sniffed = crate::utility::bulk_get_file::strip_leading_boms(&text);
308        if sniffed.trim().is_empty()
309            || crate::utility::bulk_get_file::should_treat_get_file_body_as_error(
310                sniffed,
311                &content_type,
312            )
313            || crate::utility::http_error::content_type_is_html(&content_type)
314            || crate::utility::http_error::body_looks_like_html(sniffed)
315        {
316            return Err(ZBError::api(
317                status,
318                self.redact(&message_from_body(status, &content_type, sniffed), &[]),
319            ));
320        }
321        Ok(text)
322    }
323
324    // -- argument checks -----------------------------------------------------
325
326    fn required<'a>(value: &'a str, name: &str) -> ZBResult<&'a str> {
327        if value.trim().is_empty() {
328            return Err(ZBError::ExplicitError(format!("{name} is required")));
329        }
330        Ok(value)
331    }
332
333    fn in_range(value: i64, low: i64, high: i64, name: &str) -> ZBResult<i64> {
334        if !(low..=high).contains(&value) {
335            return Err(ZBError::ExplicitError(format!(
336                "{name} must be {low} to {high}"
337            )));
338        }
339        Ok(value)
340    }
341
342    fn engagement_body(
343        c_from: &str,
344        reply_pct: i64,
345        important_pct: i64,
346        click_pct: i64,
347    ) -> ZBResult<Value> {
348        Self::required(c_from, "c_from")?;
349        Self::in_range(reply_pct, 5, 45, "reply_pct")?;
350        Self::in_range(important_pct, 5, 40, "important_pct")?;
351        Self::in_range(click_pct, 0, 70, "click_pct")?;
352        if (click_pct as f64) > important_pct as f64 * 1.75 {
353            return Err(ZBError::explicit(
354                "click_pct must be at most important_pct x 1.75",
355            ));
356        }
357        Ok(Value::Object(Map::from_iter([
358            ("c_from".into(), Value::String(c_from.to_string())),
359            ("reply_pct".into(), Value::from(reply_pct)),
360            ("important_pct".into(), Value::from(important_pct)),
361            ("click_pct".into(), Value::from(click_pct)),
362        ])))
363    }
364
365    // -- sending accounts ----------------------------------------------------
366
367    /// Every sending account of the key's team. `GET /sending-accounts`
368    pub fn list_sending_accounts(&self) -> ZBResult<Option<Value>> {
369        self.get("/sending-accounts", &HashMap::new())
370    }
371
372    /// One sending account. `GET /sending-account`
373    pub fn get_sending_account(&self, from_address: &str) -> ZBResult<Option<Value>> {
374        Self::required(from_address, "from_address")?;
375        self.get(
376            "/sending-account",
377            &HashMap::from([("from_address", from_address.to_string())]),
378        )
379    }
380
381    /// Add a from-address to warmup. `POST /sending-accounts`
382    ///
383    /// `SelfManaged` runs your own mailbox and needs `engagement_rule_id` 0-4.
384    /// `ZbManaged` has ZeroBounce provision it and takes `email_content` and
385    /// `managed_sending`; a 200 means accepted, and the mailbox is provisioned
386    /// afterwards. For `zb_managed`, prefer
387    /// [`add_zb_managed_sending_account`](Self::add_zb_managed_sending_account),
388    /// which takes every documented field.
389    #[allow(deprecated)]
390    pub fn add_sending_account(
391        &self,
392        from_address: &str,
393        onboarding_model: OnboardingModel,
394        engagement_rule_id: Option<i64>,
395        ignore_conflict: Option<bool>,
396        email_content: Option<&EmailContent>,
397        managed_sending: Option<&ManagedSending>,
398    ) -> ZBResult<Option<Value>> {
399        Self::required(from_address, "from_address")?;
400        let mut body = Map::from_iter([
401            ("from_address".into(), Value::String(from_address.into())),
402            (
403                "onboarding_model".into(),
404                Value::String(onboarding_model.as_str().into()),
405            ),
406        ]);
407
408        if onboarding_model == OnboardingModel::SelfManaged {
409            let Some(rule) = engagement_rule_id else {
410                return Err(ZBError::explicit(
411                    "engagement_rule_id is required for self_managed",
412                ));
413            };
414            body.insert(
415                "engagement_rule_id".into(),
416                Value::from(Self::in_range(rule, 0, 4, "engagement_rule_id")?),
417            );
418            if email_content.is_some() || managed_sending.is_some() {
419                return Err(ZBError::explicit(
420                    "email_content and managed_sending are for zb_managed",
421                ));
422            }
423        }
424        if let Some(flag) = ignore_conflict {
425            body.insert("ignore_conflict".into(), Value::Bool(flag));
426        }
427        // The 3.0.0 structs, mapped onto the documented fields: `website` is
428        // the API's `company_website`; `industry` and `daily_limit` are not
429        // read by the API and are dropped. A whole-hour offset stays an integer.
430        #[allow(deprecated)]
431        if let Some(content) = email_content {
432            let documented = ZbManagedEmailContent {
433                company_name: content.company_name.clone(),
434                company_website: content.website.clone(),
435                types_of_emails: content.types_of_emails.clone(),
436                ..ZbManagedEmailContent::default()
437            };
438            body.insert("email_content".into(), Self::email_content_body(&documented)?);
439        }
440        #[allow(deprecated)]
441        if let Some(sending) = managed_sending {
442            let documented = ZbManagedSending {
443                warmup_start_date: sending.warmup_start_date,
444                ..ZbManagedSending::default()
445            };
446            let mut object = Self::managed_sending_body(&documented)?;
447            if let Some(offset) = sending.timezone_offset {
448                Self::in_range(i64::from(offset), -11, 14, "timezone_offset")?;
449                if let Value::Object(map) = &mut object {
450                    map.insert("timezone_offset".into(), Value::from(offset));
451                }
452            }
453            body.insert("managed_sending".into(), object);
454        }
455        self.write("POST", "/sending-accounts", Value::Object(body))
456    }
457
458    /// Add a from-address that ZeroBounce provisions and sends from
459    /// (`zb_managed` onboarding). `POST /sending-accounts`
460    ///
461    /// `email_content` and `managed_sending` are optional and send only the
462    /// fields that are set. A 200 means the request was accepted; the mailbox
463    /// is provisioned afterwards.
464    pub fn add_zb_managed_sending_account(
465        &self,
466        from_address: &str,
467        ignore_conflict: Option<bool>,
468        email_content: Option<&ZbManagedEmailContent>,
469        managed_sending: Option<&ZbManagedSending>,
470    ) -> ZBResult<Option<Value>> {
471        Self::required(from_address, "from_address")?;
472        let mut body = Map::from_iter([
473            ("from_address".into(), Value::String(from_address.into())),
474            (
475                "onboarding_model".into(),
476                Value::String(OnboardingModel::ZbManaged.as_str().into()),
477            ),
478        ]);
479        if let Some(flag) = ignore_conflict {
480            body.insert("ignore_conflict".into(), Value::Bool(flag));
481        }
482        if let Some(content) = email_content {
483            body.insert("email_content".into(), Self::email_content_body(content)?);
484        }
485        if let Some(sending) = managed_sending {
486            body.insert("managed_sending".into(), Self::managed_sending_body(sending)?);
487        }
488        self.write("POST", "/sending-accounts", Value::Object(body))
489    }
490
491    fn email_content_body(content: &ZbManagedEmailContent) -> ZBResult<Value> {
492        let mut object = Map::new();
493        for (key, value) in [
494            ("company_name", &content.company_name),
495            ("company_website", &content.company_website),
496            ("company_description", &content.company_description),
497        ] {
498            if let Some(value) = value {
499                object.insert(key.into(), Value::String(value.clone()));
500            }
501        }
502        if !content.types_of_emails.is_empty() {
503            for kind in &content.types_of_emails {
504                if !EMAIL_TYPES.contains(&kind.as_str()) {
505                    return Err(ZBError::explicit(
506                        "types_of_emails must be transactional, newsletter and/or marketing",
507                    ));
508                }
509            }
510            object.insert(
511                "types_of_emails".into(),
512                Value::Array(
513                    content
514                        .types_of_emails
515                        .iter()
516                        .map(|kind| Value::String(kind.clone()))
517                        .collect(),
518                ),
519            );
520        }
521        if let Some(example) = &content.example_email {
522            object.insert("example_email".into(), Value::String(example.clone()));
523        }
524        Ok(Value::Object(object))
525    }
526
527    fn managed_sending_body(sending: &ZbManagedSending) -> ZBResult<Value> {
528        let mut object = Map::new();
529        if let Some(flag) = sending.weekdays_only {
530            object.insert("weekdays_only".into(), Value::Bool(flag));
531        }
532        if let Some(timezone) = &sending.timezone {
533            object.insert("timezone".into(), Value::String(timezone.clone()));
534        }
535        if let Some(offset) = sending.timezone_offset {
536            // NaN and the infinities fail the range check too.
537            if !(-11.0..=14.0).contains(&offset) {
538                return Err(ZBError::explicit("timezone_offset must be -11.0 to 14.0"));
539            }
540            object.insert("timezone_offset".into(), Value::from(offset));
541        }
542        if let Some(date) = sending.warmup_start_date {
543            object.insert(
544                "warmup_start_date".into(),
545                Value::String(date.format("%F").to_string()),
546            );
547        }
548        Ok(Value::Object(object))
549    }
550
551    /// Change an account's engagement rule, status and auto-enable flag.
552    /// `PUT /sending-accounts`. `status_id` is 0 to 8 (4 Paused, 5 Disabled).
553    pub fn update_sending_account(
554        &self,
555        from_address: &str,
556        engagement_rule_id: i64,
557        status_id: i64,
558        auto_enable: bool,
559    ) -> ZBResult<Option<Value>> {
560        Self::required(from_address, "from_address")?;
561        let body = Value::Object(Map::from_iter([
562            ("team_id".into(), Value::from(ANY_TEAM_ID)),
563            ("from_address".into(), Value::String(from_address.into())),
564            (
565                "engagement_rule_id".into(),
566                Value::from(Self::in_range(engagement_rule_id, 0, 4, "engagement_rule_id")?),
567            ),
568            (
569                "status_id".into(),
570                Value::from(Self::in_range(status_id, 0, 8, "status_id")?),
571            ),
572            ("auto_enable".into(), Value::Bool(auto_enable)),
573        ]));
574        self.write("PUT", "/sending-accounts", body)
575    }
576
577    /// Remove a sending account. `DELETE /sending-accounts`. Destructive and final.
578    pub fn delete_sending_account(&self, from_address: &str) -> ZBResult<Option<Value>> {
579        Self::required(from_address, "from_address")?;
580        self.json(
581            "DELETE",
582            "/sending-accounts",
583            &HashMap::from([("from_address", from_address.to_string())]),
584            None,
585            &[],
586        )
587    }
588
589    /// Move an account and its history to a new from-address.
590    /// `PUT /smtp-credentials` — despite the path, no SMTP credentials are stored.
591    pub fn change_from_address(
592        &self,
593        old_from_address: &str,
594        new_from_address: &str,
595    ) -> ZBResult<Option<Value>> {
596        Self::required(old_from_address, "old_from_address")?;
597        Self::required(new_from_address, "new_from_address")?;
598        let body = Value::Object(Map::from_iter([
599            ("team_id".into(), Value::from(ANY_TEAM_ID)),
600            (
601                "old_from_address".into(),
602                Value::String(old_from_address.into()),
603            ),
604            (
605                "new_from_address".into(),
606                Value::String(new_from_address.into()),
607            ),
608        ]));
609        self.write("PUT", "/smtp-credentials", body)
610    }
611
612    /// Registered from-addresses. `GET /from-addresses`
613    ///
614    /// `search_from` takes letters, digits and `. - _ @ +` only. `offset` and
615    /// `limit` go on the wire as strings.
616    pub fn list_from_addresses(
617        &self,
618        search_from: Option<&str>,
619        offset: Option<u32>,
620        limit: Option<u32>,
621    ) -> ZBResult<Option<Value>> {
622        let mut query = HashMap::new();
623        if let Some(search) = search_from {
624            if !search
625                .chars()
626                .all(|c| c.is_ascii_alphanumeric() || ".-_@+".contains(c))
627            {
628                return Err(ZBError::explicit(
629                    "search_from takes letters, digits and . - _ @ + only",
630                ));
631            }
632            query.insert("search_from", search.to_string());
633        }
634        if let Some(offset) = offset {
635            query.insert("offset", offset.to_string());
636        }
637        if let Some(limit) = limit {
638            query.insert("limit", limit.to_string());
639        }
640        self.get("/from-addresses", &query)
641    }
642
643    // -- engagement rules ----------------------------------------------------
644
645    /// -1 Custom, 0 Default, 1 Slow Pace, 2 Repair, 3 Boost, 4 Protect.
646    pub fn get_engagement_rules(&self) -> ZBResult<Option<Value>> {
647        self.get("/engagement-rules", &HashMap::new())
648    }
649
650    /// Set a standard rule (0 to 4) on an address. `PUT /engagement-rule`
651    pub fn set_engagement_rule(&self, c_from: &str, rule_id: i64) -> ZBResult<Option<Value>> {
652        Self::required(c_from, "c_from")?;
653        let body = Value::Object(Map::from_iter([(
654            "rule_id".to_string(),
655            Value::from(Self::in_range(rule_id, 0, 4, "rule_id")?),
656        )]));
657        self.json(
658            "PUT",
659            "/engagement-rule",
660            &HashMap::from([("c_from", c_from.to_string())]),
661            Some(&body),
662            &[],
663        )
664    }
665
666    /// An address's custom rule, with `can_update` and `remaining_seconds`.
667    pub fn get_custom_engagement(&self, c_from: &str) -> ZBResult<Option<Value>> {
668        Self::required(c_from, "c_from")?;
669        let path = format!(
670            "/custom-engagement/{}",
671            crate::utility::encode_path_segment(c_from.trim())
672        );
673        if c_from.trim() == "." || c_from.trim() == ".." {
674            return Err(ZBError::explicit("c_from is invalid"));
675        }
676        self.get(&path, &HashMap::new())
677    }
678
679    /// Create a custom rule. Starts a 7 day cooldown on updates.
680    pub fn create_custom_engagement(
681        &self,
682        c_from: &str,
683        reply_pct: i64,
684        important_pct: i64,
685        click_pct: i64,
686    ) -> ZBResult<Option<Value>> {
687        let body = Self::engagement_body(c_from, reply_pct, important_pct, click_pct)?;
688        self.write("POST", "/custom-engagement", body)
689    }
690
691    /// Update a custom rule. During the 7 day cooldown the API answers 429.
692    pub fn update_custom_engagement(
693        &self,
694        c_from: &str,
695        reply_pct: i64,
696        important_pct: i64,
697        click_pct: i64,
698    ) -> ZBResult<Option<Value>> {
699        let body = Self::engagement_body(c_from, reply_pct, important_pct, click_pct)?;
700        self.write("PUT", "/custom-engagement", body)
701    }
702
703    /// Delete a custom rule and fall back to standard rule 1-4.
704    pub fn delete_custom_engagement(
705        &self,
706        c_from: &str,
707        engagement_rule_id: i64,
708    ) -> ZBResult<Option<Value>> {
709        Self::required(c_from, "c_from")?;
710        let body = Value::Object(Map::from_iter([
711            ("c_from".to_string(), Value::String(c_from.into())),
712            (
713                "engagement_rule_id".to_string(),
714                Value::from(Self::in_range(engagement_rule_id, 1, 4, "engagement_rule_id")?),
715            ),
716        ]));
717        self.write("DELETE", "/custom-engagement", body)
718    }
719
720    // -- statistics, seeds and utilities -------------------------------------
721
722    /// The seed list. `GET /seeds`
723    pub fn get_seeds(&self) -> ZBResult<Option<Value>> {
724        self.get("/seeds", &HashMap::new())
725    }
726
727    /// The seed list as CSV (columns `seed,provider`). `GET /seeds/download`
728    pub fn download_seeds(&self) -> ZBResult<String> {
729        self.csv("/seeds/download", &HashMap::new())
730    }
731
732    /// Number of seeds. `GET /seed-count`
733    pub fn get_seed_count(&self) -> ZBResult<Option<Value>> {
734        self.get("/seed-count", &HashMap::new())
735    }
736
737    /// Today's warmup progress. `GET /progress-today`
738    pub fn get_progress_today(&self) -> ZBResult<Option<Value>> {
739        self.get("/progress-today", &HashMap::new())
740    }
741
742    /// Messages sent today. `GET /sent-today`
743    pub fn get_sent_today(&self) -> ZBResult<Option<Value>> {
744        self.get("/sent-today", &HashMap::new())
745    }
746
747    /// Current daily volume. `GET /emails-per-day`
748    pub fn get_emails_per_day(&self) -> ZBResult<Option<Value>> {
749        self.get("/emails-per-day", &HashMap::new())
750    }
751
752    /// Statistics for an address. An address with no history returns zeros.
753    pub fn get_statistics(&self, from_address: &str) -> ZBResult<Option<Value>> {
754        Self::required(from_address, "from_address")?;
755        self.get(
756            "/statistics",
757            &HashMap::from([("from_address", from_address.to_string())]),
758        )
759    }
760
761    /// Daily statistics between two dates, inclusive. `GET /statistics-per-day`
762    pub fn get_statistics_per_day(
763        &self,
764        from_address: &str,
765        start_date: NaiveDate,
766        end_date: NaiveDate,
767    ) -> ZBResult<Option<Value>> {
768        Self::required(from_address, "from_address")?;
769        if start_date > end_date {
770            return Err(ZBError::explicit("start_date is later than end_date"));
771        }
772        self.get(
773            "/statistics-per-day",
774            &HashMap::from([
775                ("from_address", from_address.to_string()),
776                ("start_date", start_date.format("%F").to_string()),
777                ("end_date", end_date.format("%F").to_string()),
778            ]),
779        )
780    }
781
782    /// Detailed statistics for an address. `GET /statistics-detailed`
783    pub fn get_statistics_detailed(&self, c_from: &str) -> ZBResult<Option<Value>> {
784        Self::required(c_from, "c_from")?;
785        self.get(
786            "/statistics-detailed",
787            &HashMap::from([("c_from", c_from.to_string())]),
788        )
789    }
790
791    /// An address's statistics as CSV. `GET /statistics/download`
792    pub fn download_statistics(&self, c_from: &str) -> ZBResult<String> {
793        Self::required(c_from, "c_from")?;
794        self.csv(
795            "/statistics/download",
796            &HashMap::from([("c_from", c_from.to_string())]),
797        )
798    }
799
800    /// Statistics for one from-address. `GET /from-address-statistics`
801    pub fn get_from_address_statistics(&self, from_address: &str) -> ZBResult<Option<Value>> {
802        Self::required(from_address, "from_address")?;
803        self.get(
804            "/from-address-statistics",
805            &HashMap::from([("from_address", from_address.to_string())]),
806        )
807    }
808
809    /// SPF, DKIM and DMARC status of a from-address's domain.
810    /// `GET /check-domain-dmarc`
811    ///
812    /// LIVE: pass an **email address**. The live API answers "Please provide a
813    /// valid email address" for a bare domain, although the docs describe one.
814    pub fn check_domain_dmarc(
815        &self,
816        from_address: &str,
817        dkim_selector: Option<&str>,
818    ) -> ZBResult<Option<Value>> {
819        Self::required(from_address, "from_address")?;
820        if !from_address.contains('@') {
821            return Err(ZBError::explicit(
822                "from_address must be an email address, e.g. sender@example.com",
823            ));
824        }
825        let mut query = HashMap::from([("from_address", from_address.to_string())]);
826        if let Some(selector) = dkim_selector {
827            Self::required(selector, "dkim_selector")?;
828            query.insert("dkim_selector", selector.to_string());
829        }
830        self.get("/check-domain-dmarc", &query)
831    }
832
833    /// Check that SMTP credentials connect and hand off a message.
834    /// `POST /test-smtp-configuration`
835    ///
836    /// Nothing is stored, and the test message goes to a ZeroBounce test
837    /// recipient, not `from_address`.
838    ///
839    /// LIVE: the API answers any failed SMTP login with HTTP 500. That is an
840    /// API bug. The username and password are masked in every error from here.
841    pub fn test_smtp_configuration(
842        &self,
843        from_address: &str,
844        username: &str,
845        password: &str,
846        server: &str,
847        port: u16,
848    ) -> ZBResult<Option<Value>> {
849        Self::required(from_address, "from_address")?;
850        Self::required(username, "username")?;
851        Self::required(password, "password")?;
852        Self::required(server, "server")?;
853        if port == 0 {
854            return Err(ZBError::explicit("port must be 1 to 65535"));
855        }
856        let body = Value::Object(Map::from_iter([
857            ("from_address".to_string(), Value::String(from_address.into())),
858            ("username".to_string(), Value::String(username.into())),
859            ("password".to_string(), Value::String(password.into())),
860            ("server".to_string(), Value::String(server.into())),
861            ("port".to_string(), Value::from(port)),
862        ]));
863        self.json(
864            "POST",
865            "/test-smtp-configuration",
866            &HashMap::new(),
867            Some(&body),
868            &[password, username],
869        )
870    }
871}