Skip to content

Check if an email address exists without sending any email, written in Rust. Comes with a ⚙️ HTTP backend.

fix(core)!: Clean up CheckEmailInput (#1531)

Amauryb97b9ff9b91b
diff --git a/Cargo.lock b/Cargo.lock
index a1954533..48616230 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -582,6 +582,7 @@ dependencies = [
"async-smtp",
"chrono",
"config",
+ "derive_builder 0.20.2",
"fantoccini",
"fast-socks5 0.9.6",
"futures",
@@ -888,8 +889,18 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d706e75d87e35569db781a9b5e2416cff1236a47ed380831f959382ccd5f858"
dependencies = [
- "darling_core",
- "darling_macro",
+ "darling_core 0.10.2",
+ "darling_macro 0.10.2",
+]
+
+[[package]]
+name = "darling"
+version = "0.20.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989"
+dependencies = [
+ "darling_core 0.20.10",
+ "darling_macro 0.20.10",
]
[[package]]
@@ -906,17 +917,42 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "darling_core"
+version = "0.20.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5"
+dependencies = [
+ "fnv",
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim 0.11.1",
+ "syn 2.0.66",
+]
+
[[package]]
name = "darling_macro"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72"
dependencies = [
- "darling_core",
+ "darling_core 0.10.2",
"quote",
"syn 1.0.109",
]
+[[package]]
+name = "darling_macro"
+version = "0.20.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"
+dependencies = [
+ "darling_core 0.20.10",
+ "quote",
+ "syn 2.0.66",
+]
+
[[package]]
name = "data-encoding"
version = "2.6.0"
@@ -986,25 +1022,56 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2658621297f2cf68762a6f7dc0bb7e1ff2cfd6583daef8ee0fed6f7ec468ec0"
dependencies = [
- "darling",
- "derive_builder_core",
+ "darling 0.10.2",
+ "derive_builder_core 0.9.0",
"proc-macro2",
"quote",
"syn 1.0.109",
]
+[[package]]
+name = "derive_builder"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"
+dependencies = [
+ "derive_builder_macro",
+]
+
[[package]]
name = "derive_builder_core"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2791ea3e372c8495c0bc2033991d76b512cd799d07491fbd6890124db9458bef"
dependencies = [
- "darling",
+ "darling 0.10.2",
"proc-macro2",
"quote",
"syn 1.0.109",
]
+[[package]]
+name = "derive_builder_core"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
+dependencies = [
+ "darling 0.20.10",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.66",
+]
+
+[[package]]
+name = "derive_builder_macro"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
+dependencies = [
+ "derive_builder_core 0.20.2",
+ "syn 2.0.66",
+]
+
[[package]]
name = "des"
version = "0.8.1"
@@ -2858,7 +2925,7 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f75258f75c681eb691607acdb325d0150907bc68826365b07476834df2664974"
dependencies = [
- "derive_builder",
+ "derive_builder 0.9.0",
"reqwest 0.11.27",
"serde",
"serde_derive",
@@ -3908,6 +3975,12 @@ version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
[[package]]
name = "subtle"
version = "2.5.0"
diff --git a/backend/backend_config.toml b/backend/backend_config.toml
index ba4d4ddd..8d17f2be 100644
--- a/backend/backend_config.toml
+++ b/backend/backend_config.toml
@@ -28,6 +28,10 @@ webdriver_addr = "http://localhost:9515"
# Throttle the maximum number of requests per second, per minute, per hour, an
# per day for this worker.
# All fields are optional, comment them out to disable the limit.
+#
+# Important: these throttle configurations only apply to bulk verification, and
+# not to the single /v0/check_email endpoint. The latter endpoint always
+# executes the verification immediately, regardless of the throttle settings.
[throttle]
# max_requests_per_second = 20
# max_requests_per_minute = 100
diff --git a/backend/src/check.rs b/backend/src/check.rs
deleted file mode 100644
index 182f848c..00000000
--- a/backend/src/check.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Reacher - Email Verification
-// Copyright (C) 2018-2023 Reacher
-
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Affero General Public License as published
-// by the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
-
-//! This file contains shared logic for checking one email.
-
-use check_if_email_exists::{check_email as ciee_check_email, CheckEmailInput, CheckEmailOutput};
-
-use crate::config::BackendConfig;
-
-pub async fn check_email(mut input: CheckEmailInput, config: &BackendConfig) -> CheckEmailOutput {
- input.from_email = config.from_email.clone();
- ciee_check_email(&input, &config.get_reacher_config()).await
-}
diff --git a/backend/src/config.rs b/backend/src/config.rs
index fec4c83d..f64e9ee3 100644
--- a/backend/src/config.rs
+++ b/backend/src/config.rs
@@ -8,12 +8,12 @@ pub struct BackendConfig {
/// Name of the backend.
pub backend_name: String,
- // Reacher config
+ /** Reacher config*/
pub from_email: String,
pub hello_name: String,
pub webdriver_addr: String,
- // Backend-specific config
+ /** Backend-specific config*/
/// Backend host
pub http_host: String,
/// Backend port
diff --git a/backend/src/errors.rs b/backend/src/errors.rs
deleted file mode 100644
index 0e7a7fef..00000000
--- a/backend/src/errors.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Reacher - Email Verification
-// Copyright (C) 2018-2023 Reacher
-
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Affero General Public License as published
-// by the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
-
-//! Describe a common response error to be used by all routes, should an error
-//! happen.
-
-use serde::Serialize;
-use warp::{http, reject};
-
-/// Struct describing an error response.
-#[derive(Serialize, Debug)]
-pub struct ReacherResponseError {
- #[serde(skip)]
- pub code: http::StatusCode,
- pub message: String,
-}
-
-impl reject::Reject for ReacherResponseError {}
-
-/// This function receives a `Rejection` and tries to return a custom value,
-/// otherwise simply passes the rejection along.
-pub async fn handle_rejection(err: warp::Rejection) -> Result<impl warp::Reply, warp::Rejection> {
- if let Some(err) = err.find::<ReacherResponseError>() {
- Ok((warp::reply::with_status(warp::reply::json(err), err.code),))
- } else {
- Err(err)
- }
-}
diff --git a/backend/src/http/mod.rs b/backend/src/http/mod.rs
index 0428c682..77cdfd36 100644
--- a/backend/src/http/mod.rs
+++ b/backend/src/http/mod.rs
@@ -18,6 +18,7 @@ mod v0;
mod version;
use check_if_email_exists::LOG_TARGET;
+use serde::Serialize;
use sqlx::postgres::PgPoolOptions;
use sqlx::{Pool, Postgres};
use sqlxmq::JobRunnerHandle;
@@ -26,10 +27,11 @@ use std::net::IpAddr;
use std::sync::Arc;
use tracing::info;
use warp::Filter;
+use warp::{http, reject};
use crate::config::BackendConfig;
-use super::errors;
+pub use v0::check_email::post::CheckEmailRequest;
/// Creates the routes for the HTTP server.
/// Making it public so that it can be used in tests/check_email.rs.
@@ -43,7 +45,7 @@ pub fn create_routes(
.or(v0::bulk::post::create_bulk_job(config, o.clone()))
.or(v0::bulk::get::get_bulk_job_status(o.clone()))
.or(v0::bulk::results::get_bulk_job_result(o))
- .recover(errors::handle_rejection)
+ .recover(handle_rejection)
}
/// Runs the Warp server.
@@ -128,3 +130,23 @@ pub fn with_config(
) -> impl Filter<Extract = (Arc<BackendConfig>,), Error = std::convert::Infallible> + Clone {
warp::any().map(move || config.clone())
}
+
+/// Struct describing an error response.
+#[derive(Serialize, Debug)]
+pub struct ReacherResponseError {
+ #[serde(skip)]
+ pub code: http::StatusCode,
+ pub message: String,
+}
+
+impl reject::Reject for ReacherResponseError {}
+
+/// This function receives a `Rejection` and tries to return a custom value,
+/// otherwise simply passes the rejection along.
+pub async fn handle_rejection(err: warp::Rejection) -> Result<impl warp::Reply, warp::Rejection> {
+ if let Some(err) = err.find::<ReacherResponseError>() {
+ Ok((warp::reply::with_status(warp::reply::json(err), err.code),))
+ } else {
+ Err(err)
+ }
+}
diff --git a/backend/src/http/v0/bulk/task.rs b/backend/src/http/v0/bulk/task.rs
index 3345952c..f443019e 100644
--- a/backend/src/http/v0/bulk/task.rs
+++ b/backend/src/http/v0/bulk/task.rs
@@ -17,8 +17,8 @@
//! This file implements the `POST /bulk` endpoint.
use check_if_email_exists::{
- check_email, config::ReacherConfig, CheckEmailInput, CheckEmailInputProxy, CheckEmailOutput,
- Reachable, SentryConfig, LOG_TARGET,
+ check_email, config::ReacherConfig, CheckEmailInput, CheckEmailInputBuilder,
+ CheckEmailInputProxy, CheckEmailOutput, Reachable, SentryConfig, LOG_TARGET,
};
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Postgres};
@@ -63,24 +63,25 @@ impl Iterator for TaskInputIterator {
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.body.smtp_ports.len() {
- let mut item = CheckEmailInput::new(self.body.to_email.clone());
+ let mut item = CheckEmailInputBuilder::default();
+ let mut item = item.to_email(self.body.to_email.clone());
if let Some(name) = &self.body.hello_name {
- item.set_hello_name(name.clone());
+ item = item.hello_name(name.clone());
}
if let Some(email) = &self.body.from_email {
- item.set_from_email(email.clone());
+ item = item.from_email(email.clone());
}
- item.set_smtp_port(self.body.smtp_ports[self.index]);
+ item = item.smtp_port(self.body.smtp_ports[self.index]);
if let Some(proxy) = &self.body.proxy {
- item.set_proxy(proxy.clone());
+ item = item.proxy(Some(proxy.clone()));
}
self.index += 1;
- Some(item)
+ Some(item.build().unwrap())
} else {
None
}
diff --git a/backend/src/http/v0/check_email/post.rs b/backend/src/http/v0/check_email/post.rs
index 1dd11d83..3eb3e16e 100644
--- a/backend/src/http/v0/check_email/post.rs
+++ b/backend/src/http/v0/check_email/post.rs
@@ -16,29 +16,54 @@
//! This file implements the `POST /v0/check_email` endpoint.
-use check_if_email_exists::{check_email, CheckEmailInput, LOG_TARGET};
+use check_if_email_exists::{check_email, CheckEmailInput, CheckEmailInputProxy, LOG_TARGET};
+use serde::{Deserialize, Serialize};
use std::sync::Arc;
use warp::{http, Filter};
use crate::config::BackendConfig;
-use crate::errors;
-use crate::http::{check_header, with_config};
+use crate::http::{check_header, handle_rejection, with_config, ReacherResponseError};
+
+/// The request body for the `POST /v0/check_email` endpoint.
+#[derive(Debug, Deserialize, Serialize)]
+pub struct CheckEmailRequest {
+ pub to_email: String,
+ pub from_email: Option<String>,
+ pub hello_name: Option<String>,
+ pub proxy: Option<CheckEmailInputProxy>,
+}
+
+impl CheckEmailRequest {
+ pub fn to_check_email_input(&self, config: Arc<BackendConfig>) -> CheckEmailInput {
+ CheckEmailInput {
+ to_email: self.to_email.clone(),
+ from_email: self.from_email.clone().unwrap_or(config.from_email.clone()),
+ hello_name: self.hello_name.clone().unwrap_or(config.hello_name.clone()),
+ proxy: self.proxy.clone(),
+ ..Default::default()
+ }
+ }
+}
/// The main endpoint handler that implements the logic of this route.
async fn handler(
config: Arc<BackendConfig>,
- body: CheckEmailInput,
+ body: CheckEmailRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
// The to_email field must be present
if body.to_email.is_empty() {
- Err(warp::reject::custom(errors::ReacherResponseError {
+ Err(warp::reject::custom(ReacherResponseError {
code: http::StatusCode::BAD_REQUEST,
message: "to_email field is required.".to_string(),
}))
} else {
// Run the future to check an email.
Ok(warp::reply::json(
- &check_email(&body, &config.get_reacher_config()).await,
+ &check_email(
+ &body.to_check_email_input(config.clone()),
+ &config.get_reacher_config(),
+ )
+ .await,
))
}
}
@@ -58,5 +83,5 @@ pub fn post_check_email<'a>(
.and_then(handler)
// View access logs by setting `RUST_LOG=reacher`.
.with(warp::log(LOG_TARGET))
- .recover(errors::handle_rejection)
+ .recover(handle_rejection)
}
diff --git a/backend/src/lib.rs b/backend/src/lib.rs
index 20b2c13b..408bec1b 100644
--- a/backend/src/lib.rs
+++ b/backend/src/lib.rs
@@ -14,9 +14,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-pub mod check;
pub mod config;
-mod errors;
pub mod http;
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
diff --git a/backend/tests/check_email.rs b/backend/tests/check_email.rs
index b5eac1b6..76ec6e4d 100644
--- a/backend/tests/check_email.rs
+++ b/backend/tests/check_email.rs
@@ -16,9 +16,8 @@
use std::sync::Arc;
-use check_if_email_exists::CheckEmailInput;
use reacher_backend::config::{BackendConfig, ThrottleConfig};
-use reacher_backend::http::{create_routes, REACHER_SECRET_HEADER};
+use reacher_backend::http::{create_routes, CheckEmailRequest, REACHER_SECRET_HEADER};
use warp::http::StatusCode;
use warp::test::request;
@@ -46,7 +45,7 @@ async fn test_input_foo_bar() {
.path("/v0/check_email")
.method("POST")
.header(REACHER_SECRET_HEADER, "foobar")
- .json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "foo@bar"}"#).unwrap())
+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "foo@bar"}"#).unwrap())
.reply(&create_routes(create_backend_config("foobar"), None))
.await;
@@ -60,7 +59,7 @@ async fn test_input_foo_bar_baz() {
.path("/v0/check_email")
.method("POST")
.header(REACHER_SECRET_HEADER, "foobar")
- .json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "[email protected]"}"#).unwrap())
+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())
.reply(&create_routes(create_backend_config("foobar"), None))
.await;
@@ -73,7 +72,7 @@ async fn test_reacher_secret_missing_header() {
let resp = request()
.path("/v0/check_email")
.method("POST")
- .json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "[email protected]"}"#).unwrap())
+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())
.reply(&create_routes(create_backend_config("foobar"), None))
.await;
@@ -87,7 +86,7 @@ async fn test_reacher_secret_wrong_secret() {
.path("/v0/check_email")
.method("POST")
.header(REACHER_SECRET_HEADER, "barbaz")
- .json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "[email protected]"}"#).unwrap())
+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())
.reply(&create_routes(create_backend_config("foobar"), None))
.await;
@@ -101,7 +100,7 @@ async fn test_reacher_secret_correct_secret() {
.path("/v0/check_email")
.method("POST")
.header(REACHER_SECRET_HEADER, "foobar")
- .json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "foo@bar"}"#).unwrap())
+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": "foo@bar"}"#).unwrap())
.reply(&create_routes(create_backend_config("foobar"), None))
.await;
@@ -115,21 +114,7 @@ async fn test_reacher_to_mail_empty() {
.path("/v0/check_email")
.method("POST")
.header(REACHER_SECRET_HEADER, "foobar")
- .json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": ""}"#).unwrap())
- .reply(&create_routes(create_backend_config("foobar"), None))
- .await;
-
- assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());
- assert_eq!(resp.body(), r#"{"message":"to_email field is required."}"#);
-}
-
-#[tokio::test]
-async fn test_reacher_to_mail_missing() {
- let resp = request()
- .path("/v0/check_email")
- .method("POST")
- .header(REACHER_SECRET_HEADER, "foobar")
- .json(&serde_json::from_str::<CheckEmailInput>(r#"{}"#).unwrap())
+ .json(&serde_json::from_str::<CheckEmailRequest>(r#"{"to_email": ""}"#).unwrap())
.reply(&create_routes(create_backend_config("foobar"), None))
.await;
diff --git a/cli/src/main.rs b/cli/src/main.rs
index 7da7c954..f9adb842 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -15,8 +15,8 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use check_if_email_exists::{
- check_email, config::ReacherConfig, CheckEmailInput, CheckEmailInputProxy, GmailVerifMethod,
- HotmailVerifMethod, YahooVerifMethod,
+ check_email, config::ReacherConfig, CheckEmailInputBuilder, CheckEmailInputProxy,
+ GmailVerifMethod, HotmailVerifMethod, YahooVerifMethod,
};
use clap::Parser;
use once_cell::sync::Lazy;
@@ -89,25 +89,28 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let to_email = &CONF.to_email;
- let mut input = CheckEmailInput::new(to_email.clone());
- input
- .set_from_email(CONF.from_email.clone())
- .set_hello_name(CONF.hello_name.clone())
- .set_smtp_port(CONF.smtp_port)
- .set_yahoo_verif_method(CONF.yahoo_verif_method)
- .set_gmail_verif_method(CONF.gmail_verif_method)
- .set_hotmail_verif_method(CONF.hotmail_verif_method)
- .set_check_gravatar(CONF.check_gravatar)
- .set_haveibeenpwned_api_key(CONF.haveibeenpwned_api_key.clone());
+ let mut input = CheckEmailInputBuilder::default();
+ let mut input = input
+ .to_email(to_email.clone())
+ .from_email(CONF.from_email.clone())
+ .hello_name(CONF.hello_name.clone())
+ .smtp_port(CONF.smtp_port)
+ .yahoo_verif_method(CONF.yahoo_verif_method)
+ .gmail_verif_method(CONF.gmail_verif_method)
+ .hotmail_verif_method(CONF.hotmail_verif_method)
+ .check_gravatar(CONF.check_gravatar)
+ .haveibeenpwned_api_key(CONF.haveibeenpwned_api_key.clone());
if let Some(proxy_host) = &CONF.proxy_host {
- input.set_proxy(CheckEmailInputProxy {
+ input = input.proxy(Some(CheckEmailInputProxy {
host: proxy_host.clone(),
port: CONF.proxy_port,
username: CONF.proxy_username.clone(),
password: CONF.proxy_password.clone(),
- });
+ }));
}
+ let input = input.build()?;
+
let config = ReacherConfig {
backend_name: "reacher-cli".to_string(),
..Default::default()
diff --git a/core/Cargo.toml b/core/Cargo.toml
index f64db01f..4c2593d6 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -16,8 +16,9 @@ repository = "https://github.com/reacherhq/check-if-email-exists"
async-native-tls = { version = "0.4", default-features = false }
async-recursion = "1.0.5"
async-smtp = { version = "0.6.0", features = ["socks5"] }
-chrono = "0.4.31"
+chrono = { version = "0.4.31", features = ["serde"] }
config = "0.14"
+derive_builder = "0.20"
fantoccini = { version = "0.21.2" }
futures = { version = "0.3.30" }
fast-socks5 = "0.9.2"
diff --git a/core/src/config.rs b/core/src/config.rs
index 71a60450..d2ef55a1 100644
--- a/core/src/config.rs
+++ b/core/src/config.rs
@@ -14,7 +14,8 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-use crate::SentryConfig;
+#[cfg(feature = "sentry")]
+use crate::util::sentry::SentryConfig;
/// Configuration needed to run Reacher.
#[derive(Debug)]
@@ -33,7 +34,7 @@ impl Default for ReacherConfig {
backend_name: "backend-dev".into(),
webdriver_addr: "http://localhost:9515".into(),
#[cfg(feature = "sentry")]
- sentry: Default::default(),
+ sentry: None,
}
}
}
diff --git a/core/src/lib.rs b/core/src/lib.rs
index 1fc2d622..6afb4994 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -34,30 +34,31 @@
//! - Catch-all address. Is this email address a catch-all address?
//!
//! ```rust
-//! use check_if_email_exists::{check_email, CheckEmailInput, CheckEmailInputProxy};
+//! use check_if_email_exists::{check_email, CheckEmailInputBuilder, CheckEmailInputProxy};
//! use check_if_email_exists::config::ReacherConfig;
//!
//! async fn check() {
//! // Let's say we want to test the deliverability of [email protected].
-//! let mut input = CheckEmailInput::new("[email protected]".into());
-//!
-//! // Optionally, we can also tweak the configuration parameters used in the
-//! // verification.
-//! input
-//! .set_from_email("[email protected]".into()) // Used in the `MAIL FROM:` command
-//! .set_hello_name("example.org".into()) // Used in the `EHLO` command
-//! .set_smtp_port(587) // Use port 587 instead of 25
-//! .set_proxy(CheckEmailInputProxy { // Use a SOCKS5 proxy to verify the email
+//! let input = CheckEmailInputBuilder::default()
+//! .to_email("[email protected]".into())
+//! // Optionally, we can also tweak the configuration parameters used in the
+//! // verification.
+//! .from_email("[email protected]".into()) // Used in the `MAIL FROM:` command
+//! .hello_name("example.org".into()) // Used in the `EHLO` command
+//! .smtp_port(587) // Use port 587 instead of 25
+//! .proxy(Some(CheckEmailInputProxy { // Use a SOCKS5 proxy to verify the email
//! host: "my-proxy.io".into(),
//! port: 1080,
-//! username: None, // You can also set it non-empty
+//! username: None, // You can also set it non-empty
//! password: None
-//! });
+//! }))
+//! .build()
+//! .unwrap();
//!
//! // We also need to set some configuration parameters.
//! let config = ReacherConfig {
-//! backend_name: "my-backend".into(),
-//! ..Default::default()
+//! backend_name: "my-backend".into(),
+//! ..Default::default()
//! };
//!
//! // Verify this input, using async/await syntax.
diff --git a/core/src/smtp/error.rs b/core/src/smtp/error.rs
index 86efc9a5..a41ed55f 100644
--- a/core/src/smtp/error.rs
+++ b/core/src/smtp/error.rs
@@ -43,8 +43,6 @@ pub enum SmtpError {
HeadlessError(HeadlessError),
/// Error when verifying a Microsoft 365 email via HTTP request.
Microsoft365Error(Microsoft365Error),
- /// Email is in the `skipped_domains` parameter.
- SkippedDomain(String),
}
impl From<SocksError> for SmtpError {
diff --git a/core/src/smtp/gmail.rs b/core/src/smtp/gmail.rs
index 49a95bd6..d33399a3 100644
--- a/core/src/smtp/gmail.rs
+++ b/core/src/smtp/gmail.rs
@@ -85,13 +85,18 @@ pub fn is_gmail(host: &str) -> bool {
mod tests {
use std::str::FromStr;
+ use crate::CheckEmailInputBuilder;
+
use super::*;
#[tokio::test]
#[ignore] // ref: https://github.com/reacherhq/check-if-email-exists/issues/1431
async fn should_return_is_deliverable_true() {
let to_email = EmailAddress::from_str("[email protected]").unwrap();
- let input = CheckEmailInput::new("[email protected]".to_owned());
+ let input = CheckEmailInputBuilder::default()
+ .to_email("[email protected]".to_owned())
+ .build()
+ .unwrap();
let smtp_details = check_gmail(&to_email, &input).await;
diff --git a/core/src/smtp/mod.rs b/core/src/smtp/mod.rs
index 20af6133..4efe44c6 100644
--- a/core/src/smtp/mod.rs
+++ b/core/src/smtp/mod.rs
@@ -101,17 +101,6 @@ pub async fn check_smtp(
let host = host.to_string();
let to_email_str = to_email.to_string();
- if input.skipped_domains.iter().any(|d| host.contains(d)) {
- return (
- Err(SmtpError::SkippedDomain(format!(
- "Reacher currently cannot verify emails from @{domain}"
- ))),
- SmtpDebug {
- verif_method: VerifMethod::Skipped,
- },
- );
- }
-
if is_hotmail(&host) {
match (&input.hotmail_verif_method, is_microsoft365(&host)) {
(HotmailVerifMethod::OneDriveApi, true) => {
@@ -206,9 +195,8 @@ pub async fn check_smtp(
#[cfg(test)]
mod tests {
- use crate::config::ReacherConfig;
-
- use super::{check_smtp, CheckEmailInput, SmtpConnection, SmtpError};
+ use super::{check_smtp, SmtpConnection, SmtpError};
+ use crate::{config::ReacherConfig, CheckEmailInputBuilder};
use async_smtp::{smtp::error::Error, EmailAddress};
use hickory_proto::rr::Name;
use std::{str::FromStr, time::Duration};
@@ -220,9 +208,12 @@ mod tests {
let to_email = EmailAddress::from_str("[email protected]").unwrap();
let host = Name::from_str("alt4.aspmx.l.google.com.").unwrap();
- let mut input = CheckEmailInput::default();
- input.set_gmail_verif_method(crate::GmailVerifMethod::Smtp);
- input.set_smtp_timeout(Some(Duration::from_millis(1)));
+ let input = CheckEmailInputBuilder::default()
+ .to_email("[email protected]".into())
+ .gmail_verif_method(crate::GmailVerifMethod::Smtp)
+ .smtp_timeout(Some(Duration::from_millis(1)))
+ .build()
+ .unwrap();
let config = ReacherConfig::default();
let (res, smtp_debug) = runtime.block_on(check_smtp(
@@ -246,29 +237,4 @@ mod tests {
_ => panic!("check_smtp did not time out"),
}
}
-
- #[test]
- fn should_skip_domains() {
- let runtime = Runtime::new().unwrap();
-
- let to_email = EmailAddress::from_str("[email protected]").unwrap();
- let host = Name::from_str("mx01.mail.icloud.com.").unwrap();
- let mut input = CheckEmailInput::default();
- input.set_skipped_domains(vec![".mail.icloud.com.".into()]);
- let config = ReacherConfig::default();
-
- let (res, smtp_debug) = runtime.block_on(check_smtp(
- &to_email,
- &host,
- 25,
- "icloud.com",
- &input,
- &config,
- ));
- assert_eq!(smtp_debug.verif_method, super::VerifMethod::Skipped);
- match res {
- Err(SmtpError::SkippedDomain(_)) => (),
- r => panic!("{:?}", r),
- }
- }
}
diff --git a/core/src/util/input_output.rs b/core/src/util/input_output.rs
index b6fc44bc..e66cd775 100644
--- a/core/src/util/input_output.rs
+++ b/core/src/util/input_output.rs
@@ -19,6 +19,7 @@ use std::time::{Duration, SystemTime};
use async_smtp::{ClientSecurity, ClientTlsParameters};
use chrono::{DateTime, Utc};
+use derive_builder::Builder;
use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer};
use crate::misc::{MiscDetails, MiscError};
@@ -154,8 +155,8 @@ impl FromStr for HotmailVerifMethod {
/// Builder pattern for the input argument into the main `email_exists`
/// function.
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(default)]
+#[derive(Builder, Debug, Clone, Deserialize, Serialize)]
+#[builder(default)]
pub struct CheckEmailInput {
/// The email to validate.
pub to_email: String,
@@ -193,12 +194,13 @@ pub struct CheckEmailInput {
///
/// Defaults to Headless.
pub hotmail_verif_method: HotmailVerifMethod,
- // Whether to check if a gravatar image is existing for the given email.
- //
- // Defaults to false.
+ /// Whether to check if a gravatar image is existing for the given email.
+ /// Adds a bit of latency to the verification process.
+ ///
+ /// Defaults to false.
pub check_gravatar: bool,
/// Check if a the email address is present in HaveIBeenPwned API.
- // If the api_key is filled, HaveIBeenPwned API is checked
+ /// If the api_key is filled, HaveIBeenPwned API is checked
pub haveibeenpwned_api_key: Option<String>,
/// Number of retries of SMTP connections to do. Setting to 2 might bypass
/// greylisting on some servers, but takes more time.
@@ -209,25 +211,6 @@ pub struct CheckEmailInput {
///
/// Defaults to Opportunistic.
pub smtp_security: SmtpSecurity,
- /// **IMPORTANT:** This is a beta feature, and might be completely removed,
- /// or moved somewhere else, before the next release.
- ///
- /// List of domains to skip when doing an SMTP connection, because we know
- /// they return "unknown". For each string in this list, we check if the MX
- /// record **contains** the string; if yes, we return an error saying the
- /// SMTP verification is skipped.
- ///
- /// Related issue: https://github.com/reacherhq/check-if-email-exists/issues/937
- ///
- /// ## Example
- ///
- /// If you want to skip Zoho emails, it's good enough to ".zoho.com." to
- /// the list. This way it will skip all Zoho emails as their MX records
- /// show "mx{N}.zoho.com.". Simply putting "zoho" might give false
- /// positives if you have an email provider like "mycustomzoho.com".
- ///
- /// Defaults to: [""]
- pub skipped_domains: Vec<String>,
}
impl Default for CheckEmailInput {
@@ -246,154 +229,8 @@ impl Default for CheckEmailInput {
check_gravatar: false,
haveibeenpwned_api_key: None,
retries: 1,
- skipped_domains: vec![],
- }
- }
-}
-
-impl CheckEmailInput {
- /// Create a new CheckEmailInput.
- pub fn new(to_email: String) -> CheckEmailInput {
- CheckEmailInput {
- to_email,
- ..Default::default()
}
}
-
- /// Set the email to use in the `MAIL FROM:` SMTP command. Defaults to
- /// `[email protected]` if not explicitly set.
- #[deprecated(since = "0.8.24", note = "Please use set_from_email instead")]
- pub fn from_email(&mut self, email: String) -> &mut CheckEmailInput {
- self.from_email = email;
- self
- }
-
- /// Set the email to use in the `MAIL FROM:` SMTP command. Defaults to
- /// `[email protected]` if not explicitly set.
- pub fn set_from_email(&mut self, email: String) -> &mut CheckEmailInput {
- self.from_email = email;
- self
- }
-
- /// Set the name to use in the `EHLO:` SMTP command. Defaults to `localhost`
- /// if not explicitly set.
- #[deprecated(since = "0.8.24", note = "Please use set_hello_name instead")]
- pub fn hello_name(&mut self, name: String) -> &mut CheckEmailInput {
- self.hello_name = name;
- self
- }
-
- /// Set the name to use in the `EHLO:` SMTP command. Defaults to `localhost`
- /// if not explicitly set.
- pub fn set_hello_name(&mut self, name: String) -> &mut CheckEmailInput {
- self.hello_name = name;
- self
- }
-
- /// Use the specified SOCK5 proxy to perform email verification.
- #[deprecated(since = "0.8.24", note = "Please use set_proxy instead")]
- pub fn proxy(&mut self, proxy_host: String, proxy_port: u16) -> &mut CheckEmailInput {
- self.proxy = Some(CheckEmailInputProxy {
- host: proxy_host,
- port: proxy_port,
- ..Default::default()
- });
- self
- }
-
- /// Use the specified SOCK5 proxy to perform email verification.
- pub fn set_proxy(&mut self, proxy: CheckEmailInputProxy) -> &mut CheckEmailInput {
- self.proxy = Some(proxy);
- self
- }
-
- /// Set the number of SMTP retries to do.
- pub fn set_retries(&mut self, retries: usize) -> &mut CheckEmailInput {
- self.retries = retries;
- self
- }
-
- /// Add optional timeout for the SMTP verification step.
- #[deprecated(since = "0.8.24", note = "Please use set_smtp_timeout instead")]
- pub fn smtp_timeout(&mut self, duration: Duration) -> &mut CheckEmailInput {
- self.smtp_timeout = Some(duration);
- self
- }
-
- /// Change the SMTP port.
- pub fn set_smtp_port(&mut self, port: u16) -> &mut CheckEmailInput {
- self.smtp_port = port;
- self
- }
-
- /// Set the SMTP client security to use for TLS.
- pub fn set_smtp_security(&mut self, smtp_security: SmtpSecurity) -> &mut CheckEmailInput {
- self.smtp_security = smtp_security;
- self
- }
-
- /// Add optional timeout for the SMTP verification step. This is the
- /// timeout for _each_ SMTP connection attempt, not for the whole email
- /// verification process.
- pub fn set_smtp_timeout(&mut self, duration: Option<Duration>) -> &mut CheckEmailInput {
- self.smtp_timeout = duration;
- self
- }
-
- /// Set whether to use Yahoo's API, headless navigator, or connecting
- /// directly to their SMTP servers. Defaults to Headless.
- pub fn set_yahoo_verif_method(
- &mut self,
- verif_method: YahooVerifMethod,
- ) -> &mut CheckEmailInput {
- self.yahoo_verif_method = verif_method;
- self
- }
-
- /// Set whether to use Gmail's API or connecting directly to their SMTP
- /// servers. Defaults to false.
- pub fn set_gmail_verif_method(
- &mut self,
- verif_method: GmailVerifMethod,
- ) -> &mut CheckEmailInput {
- self.gmail_verif_method = verif_method;
- self
- }
-
- /// Set whether to use Microsoft 365's OneDrive API, a headless navigator,
- /// or connecting directly to their SMTP servers for hotmail addresse.
- /// Defaults to Headless.
- pub fn set_hotmail_verif_method(
- &mut self,
- verif_method: HotmailVerifMethod,
- ) -> &mut CheckEmailInput {
- self.hotmail_verif_method = verif_method;
- self
- }
-
- /// Whether to check if a gravatar image is existing for the given email.
- /// Defaults to false.
- pub fn set_check_gravatar(&mut self, check_gravatar: bool) -> &mut CheckEmailInput {
- self.check_gravatar = check_gravatar;
- self
- }
-
- /// Whether to haveibeenpwned' API for the given email
- /// check only if the api_key is set.
- pub fn set_haveibeenpwned_api_key(&mut self, api_key: Option<String>) -> &mut CheckEmailInput {
- self.haveibeenpwned_api_key = api_key;
- self
- }
-
- /// **IMPORTANT:** This is a beta feature, and might be completely removed,
- /// or moved somewhere else, before the next release.
- ///
- /// List of domains to skip when doing an SMTP connection, because we know
- /// they return "unknown".
- pub fn set_skipped_domains(&mut self, domains: Vec<String>) -> &mut CheckEmailInput {
- self.skipped_domains = domains;
- self
- }
}
/// An enum to describe how confident we are that the recipient address is