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";
const ANY_TEAM_ID: i64 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OnboardingModel {
SelfManaged,
ZbManaged,
}
impl OnboardingModel {
fn as_str(self) -> &'static str {
match self {
OnboardingModel::SelfManaged => "self_managed",
OnboardingModel::ZbManaged => "zb_managed",
}
}
}
#[deprecated(
note = "use ZbManagedEmailContent with ZeroBounceWarmup::add_zb_managed_sending_account"
)]
#[derive(Debug, Clone, Default)]
pub struct EmailContent {
pub types_of_emails: Vec<String>,
pub industry: Option<String>,
pub company_name: Option<String>,
pub website: Option<String>,
}
#[deprecated(
note = "use ZbManagedSending with ZeroBounceWarmup::add_zb_managed_sending_account"
)]
#[derive(Debug, Clone, Default)]
pub struct ManagedSending {
pub timezone_offset: Option<i32>,
pub warmup_start_date: Option<NaiveDate>,
pub daily_limit: Option<u32>,
}
#[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>,
pub types_of_emails: Vec<String>,
pub example_email: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct ZbManagedSending {
pub weekdays_only: Option<bool>,
pub timezone: Option<String>,
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,
}
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 {
pub fn new(api_key: &str) -> ZBResult<Self> {
Self::with_base_url(api_key, DEFAULT_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)?;
crate::parse_request_url(base_url).map_err(|error| match error.to_string().as_str() {
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()?,
})
}
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 {
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();
if (300..400).contains(&status) {
return Err(ZBError::api(
status,
crate::utility::http_error::REDIRECT_REFUSED_MESSAGE,
));
}
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();
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 {
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))
}
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)?;
if status == 204 || text.is_empty() {
return Ok(None);
}
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), &[])
}
fn csv(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<String> {
let (status, content_type, text) = self.send("GET", path, query, None, &[])?;
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)
}
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)),
])))
}
pub fn list_sending_accounts(&self) -> ZBResult<Option<Value>> {
self.get("/sending-accounts", &HashMap::new())
}
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())]),
)
}
#[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));
}
#[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))
}
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 {
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))
}
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)
}
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,
&[],
)
}
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)
}
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)
}
pub fn get_engagement_rules(&self) -> ZBResult<Option<Value>> {
self.get("/engagement-rules", &HashMap::new())
}
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),
&[],
)
}
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())
}
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)
}
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)
}
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)
}
pub fn get_seeds(&self) -> ZBResult<Option<Value>> {
self.get("/seeds", &HashMap::new())
}
pub fn download_seeds(&self) -> ZBResult<String> {
self.csv("/seeds/download", &HashMap::new())
}
pub fn get_seed_count(&self) -> ZBResult<Option<Value>> {
self.get("/seed-count", &HashMap::new())
}
pub fn get_progress_today(&self) -> ZBResult<Option<Value>> {
self.get("/progress-today", &HashMap::new())
}
pub fn get_sent_today(&self) -> ZBResult<Option<Value>> {
self.get("/sent-today", &HashMap::new())
}
pub fn get_emails_per_day(&self) -> ZBResult<Option<Value>> {
self.get("/emails-per-day", &HashMap::new())
}
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())]),
)
}
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()),
]),
)
}
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())]),
)
}
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())]),
)
}
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())]),
)
}
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)
}
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],
)
}
}