Skip to content

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

feat!: Allow multiple proxies (#1562)

Amauryeed5a1536af3
diff --git a/Cargo.lock b/Cargo.lock
index fa0b0ffb..91bcdd1d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -601,7 +601,7 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "check-if-email-exists"
-version = "0.10.2"
+version = "0.11.0"
dependencies = [
"anyhow",
"async-recursion",
@@ -633,7 +633,7 @@ dependencies = [
[[package]]
name = "check-if-email-exists-cli"
-version = "0.10.2"
+version = "0.11.0"
dependencies = [
"anyhow",
"check-if-email-exists",
@@ -3062,7 +3062,7 @@ dependencies = [
[[package]]
name = "reacher_backend"
-version = "0.10.2"
+version = "0.11.0"
dependencies = [
"anyhow",
"async-smtp",
@@ -3079,6 +3079,7 @@ dependencies = [
"sentry-anyhow",
"serde",
"serde_json",
+ "serial_test",
"sqlx",
"sqlxmq",
"thiserror 1.0.69",
@@ -3094,7 +3095,7 @@ dependencies = [
[[package]]
name = "reacher_sqs"
-version = "0.10.2"
+version = "0.11.0"
dependencies = [
"check-if-email-exists",
"lambda_runtime",
@@ -3465,6 +3466,15 @@ dependencies = [
"cipher",
]
+[[package]]
+name = "scc"
+version = "2.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea091f6cac2595aa38993f04f4ee692ed43757035c36e67c180b6828356385b1"
+dependencies = [
+ "sdd",
+]
+
[[package]]
name = "schannel"
version = "0.1.27"
@@ -3507,6 +3517,12 @@ dependencies = [
"untrusted",
]
+[[package]]
+name = "sdd"
+version = "3.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b07779b9b918cc05650cb30f404d4d7835d26df37c235eded8a6832e2fb82cca"
+
[[package]]
name = "security-framework"
version = "2.11.1"
@@ -3674,6 +3690,31 @@ dependencies = [
"serde",
]
+[[package]]
+name = "serial_test"
+version = "3.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b258109f244e1d6891bf1053a55d63a5cd4f8f4c30cf9a1280989f80e7a1fa9"
+dependencies = [
+ "futures",
+ "log",
+ "once_cell",
+ "parking_lot",
+ "scc",
+ "serial_test_derive",
+]
+
+[[package]]
+name = "serial_test_derive"
+version = "3.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d69265a08751de7844521fd15003ae0a888e035773ba05695c5c759a6f89eef"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.90",
+]
+
[[package]]
name = "sha1"
version = "0.10.6"
diff --git a/backend/Cargo.toml b/backend/Cargo.toml
index 39ba7ec8..d6460846 100644
--- a/backend/Cargo.toml
+++ b/backend/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "reacher_backend"
-version = "0.10.2"
+version = "0.11.0"
edition = "2018"
license = "AGPL-3.0"
publish = false
@@ -46,4 +46,5 @@ uuid = "1.10"
warp = "0.3"
[dev-dependencies]
+serial_test = "3.2"
toml = "0.8"
diff --git a/backend/backend_config.toml b/backend/backend_config.toml
index f353a363..72c420d9 100644
--- a/backend/backend_config.toml
+++ b/backend/backend_config.toml
@@ -21,23 +21,6 @@ http_port = 8080
# Env variable: RCH__HEADER_SECRET
# header_secret = "my-secret"
-# Name to use during the EHLO/HELO command in the SMTP conversation.
-# Ideally, this should match the reverse DNS of the server's IP address.
-#
-# Env variable: RCH__HELLO_NAME
-hello_name = "localhost"
-
-# Email to use during the MAIL FROM command in the SMTP conversation.
-# Ideally, the domain of this email should match the "hello_name" above.
-#
-# Env variable: RCH__FROM_EMAIL
-from_email = "hello@localhost"
-
-# Timeout for each SMTP connection, in seconds. Leaving it commented out will
-# not set a timeout, i.e. the connection will wait indefinitely.
-#
-# Env variable: RCH__SMTP_TIMEOUT
-# smtp_timeout = 45
# Optional Sentry DSN. If set, all errors will be sent to Sentry.
#
@@ -55,10 +38,12 @@ webdriver_addr = "http://localhost:9515"
# Env variable: RCH__WEBDRIVER__BINARY
# binary = "/usr/bin/google-chrome"
-# Uncomment the lines below to route all SMTP verification requests
-# through a specified proxy. Note that the proxy must be a SOCKS5 proxy to work
-# with the SMTP protocol. This proxy will not be used for headless
-# verifications.
+# Deprecated: use the "proxies" configuration below instead.
+#
+# Uncomment the lines below to define a proxy called "default". If you want to
+# use a proxy, you can set the `proxy` field in the `verif_method` section
+# below to "default". Not setting it will NOT apply this default proxy to
+# verifications though.
#
# The username and password are optional and only needed if the proxy requires
# authentication.
@@ -75,24 +60,127 @@ webdriver_addr = "http://localhost:9515"
# username = "my-username"
# password = "my-password"
-# Verification method to use for each email provider. Available methods are:
-# "smtp", "headless", and "api". Note that not all methods are supported by
-# all email providers.
+# Verification method to use for each email provider. Each email provider can
+# be verified using one of the following methods:
+# - Gmail: smtp
+# - Hotmail B2B: smtp
+# - Hotmail B2C: headless or smtp
+# - Yahoo: headless or smtp
+# - Everything else: smtp
+#
+# For the email providers you choose to verify using the "smtp" method, you
+# may add additional configuration, such as hello_name, from_email, and
+# whether to use a proxy or not.
+#
+# If using proxies, the list of proxies must be defined in the "proxies"
+# section below, with a unique name for each proxy such as "proxy1", "proxy2",
+# etc. Then, in the email provider's SMTP configuration, set the value to the
+# name of the proxy to use.
[verif_method]
-# Gmail currently only supports the "smtp" method.
-#
-# Env variable: RCH__VERIF_METHOD__GMAIL
-gmail = "smtp"
-# Hotmail B2B currently only supports the "smtp" method.
-#
-# Env variable: RCH__VERIF_METHOD__HOTMAILB2B
-hotmailb2b = "smtp"
-# Hotmail B2C supports both "headless" and "smtp" methods. The "headless"
-# method is recommended.
-hotmailb2c = "headless"
-# Yahoo supports both "headless" and "smtp" methods. The "headless" method is
-# recommended.
-yahoo = "headless"
+# Use the "proxies" configuration below to route SMTP verification requests
+# through a specified proxy.
+#
+# Reacher allows you to configure multiple proxies, each with a unique name.
+# We recommend simply using "proxy1", "proxy2", etc. as the proxy names.
+#
+# In the `verif_method` section below, you can specify which proxy to use for
+# each email provider. For example, to use "proxy1" for Gmail and "proxy2" for
+# Yahoo, set the `gmail` field to "proxy1" and the `yahoo` field to "proxy2".
+[verif_method.proxies]
+# Uncomment the lines below to configure a proxy. The username and password are
+# optional and only needed if the proxy requires authentication.
+#
+# Env variables:
+# - RCH__VERIF_METHOD__PROXIES__PROXY1__HOST
+# - RCH__VERIF_METHOD__PROXIES__PROXY1__PORT
+# - RCH__VERIF_METHOD__PROXIES__PROXY1__USERNAME
+# - RCH__VERIF_METHOD__PROXIES__PROXY1__PASSWORD
+# proxy1 = { host = "my.proxy1.com", port = 1080, username = "my-username1", password = "my-password1" }
+# proxy2 = { host = "my.proxy2.com", port = 1081 }
+
+[verif_method.gmail]
+# Verification method to use for Gmail. Gmail only supports the "smtp" method.
+# You can add additional configuration such as hello_name, from_email, and
+# whether to use a proxy or not, by uncommenting the lines below.
+#
+# Env variable: RCH__VERIF_METHOD__GMAIL__TYPE
+type = "smtp"
+# The proxy to use to verify Gmail. If set, it must match one of the names
+# defined in the "proxies" section above.
+#
+# Env variable: RCH__VERIF_METHOD__GMAIL__PROXY
+# proxy = "proxy1"
+
+# Name to use during the EHLO/HELO command in the SMTP conversation.
+# Ideally, this should match the reverse DNS of the server's IP address.
+#
+# Env variable: RCH__VERIF_METHOD__GMAIL__HELLO_NAME
+# hello_name = "my-domain.com"
+
+# Email to use during the MAIL FROM command in the SMTP conversation.
+# Ideally, the domain of this email should match the "hello_name" above.
+#
+# Env variable: RCH__VERIF_METHOD__GMAIL__FROM_EMAIL
+# from_email = "[email protected]"
+
+# Timeout for each SMTP connection, in seconds. Leaving it commented out will
+# not set a timeout, i.e. the connection will wait indefinitely. Both fields
+# secs and nanos must be set.
+#
+# Env variable: RCH__VERIF_METHOD__GMAIL__SMTP_TIMEOUT
+# smtp_timeout = { secs = 25, nanos = 0 }
+
+# Number of retries for each email verification. Leaving it commented out will
+# default to 1 retry.
+#
+# Env variable: RCH__VERIF_METHOD__GMAIL__RETRIES
+# retries = 2
+
+[verif_method.hotmailb2b]
+# Verification method to use for Hotmail B2B. Hotmail B2B only supports the
+# "smtp" method. You may copy the configuration from the Gmail section above to
+# apply them here.
+#
+# Env variable: RCH__VERIF_METHOD__HOTMAILB2B__TYPE
+type = "smtp"
+# proxy = "proxy1"
+
+[verif_method.hotmailb2c]
+# Verification method to use for Hotmail B2C. Hotmail B2C supports both the
+# "headless" and "smtp" methods. The "headless" method is recommended.
+#
+# Env variable: RCH__VERIF_METHOD__HOTMAILB2C__TYPE
+type = "headless"
+
+[verif_method.mimecast]
+# Verification method to use for emails behind Mimecast. Mimecast only supports
+# the "smtp" method. You may copy the configuration from the Gmail section above
+# to apply them here.
+#
+# Env variable: RCH__VERIF_METHOD__MIMECAST__TYPE
+type = "smtp"
+
+[verif_method.proofpoint]
+# Verification method to use for emails behind Proofpoint. Proofpoint only supports
+# the "smtp" method. You may copy the configuration from the Gmail section above
+# to apply them here.
+#
+# Env variable: RCH__VERIF_METHOD__PROOFPOINT__TYPE
+type = "smtp"
+
+[verif_method.yahoo]
+# Verification method to use for Yahoo. Yahoo supports both the "headless" and
+# "smtp" methods. The "headless" method is recommended.
+#
+# Env variable: RCH__VERIF_METHOD__YAHOO__TYPE
+type = "headless"
+
+[verif_method.everything_else]
+# Verification method to use for all other email providers. By default, all
+# other emails will be verified using the "smtp" method. You may copy the
+# configuration from the Gmail section above to apply them here.
+type = "smtp"
+# proxy = "proxy1"
# Throttle the maximum number of requests per second, per minute, per hour, and
# per day for this worker.
diff --git a/backend/src/config.rs b/backend/src/config.rs
index 89aee436..08f00089 100644
--- a/backend/src/config.rs
+++ b/backend/src/config.rs
@@ -19,15 +19,15 @@ use crate::throttle::ThrottleManager;
use crate::worker::do_work::TaskWebhook;
use crate::worker::setup_rabbit_mq;
use anyhow::{bail, Context};
-use check_if_email_exists::{
- CheckEmailInputProxy, GmailVerifMethod, HotmailB2BVerifMethod, HotmailB2CVerifMethod,
- WebdriverConfig, YahooVerifMethod, LOG_TARGET,
-};
+use check_if_email_exists::smtp::verif_method::VerifMethod;
+use check_if_email_exists::{CheckEmailInputProxy, WebdriverConfig, LOG_TARGET};
use config::Config;
use lapin::Channel;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
+use std::collections::HashMap;
use std::sync::Arc;
+use std::time::Duration;
use tracing::warn;
#[derive(Debug, Serialize, Deserialize)]
@@ -35,15 +35,18 @@ pub struct BackendConfig {
/// Name of the backend.
pub backend_name: String,
- /** Reacher config*/
- pub from_email: String,
- pub hello_name: String,
- pub webdriver_addr: String,
- pub webdriver: WebdriverConfig,
+ // This field is deprecated, but kept for backwards compatibility. If set,
+ // it will be moved to the "default" proxy in the `verif_method.proxies`
+ // field.
+ #[deprecated]
pub proxy: Option<CheckEmailInputProxy>,
- /// Verification method configuration.
- pub verif_method: VerifMethodConfig,
+ /// Verification methods per email provider.
+ pub verif_method: VerifMethod,
+
+ /// Webdriver configuration.
+ pub webdriver_addr: String,
+ pub webdriver: WebdriverConfig,
/** Backend-specific config*/
/// Backend host
@@ -52,9 +55,6 @@ pub struct BackendConfig {
pub http_port: u16,
/// Shared secret between a trusted client and the backend.
pub header_secret: Option<String>,
- /// Timeout for each SMTP connection, in seconds. Leaving it commented out
- /// will not set a timeout, i.e. the connection will wait indefinitely.
- pub smtp_timeout: Option<u64>,
/// Sentry DSN to report errors to
pub sentry_dsn: Option<String>,
@@ -86,16 +86,14 @@ impl BackendConfig {
pub fn empty() -> Self {
Self {
backend_name: "".to_string(),
- from_email: "".to_string(),
- hello_name: "".to_string(),
webdriver_addr: "".to_string(),
webdriver: WebdriverConfig::default(),
+ #[allow(deprecated)]
proxy: None,
- verif_method: VerifMethodConfig::default(),
+ verif_method: VerifMethod::default(),
http_host: "127.0.0.1".to_string(),
http_port: 8080,
header_secret: None,
- smtp_timeout: None,
sentry_dsn: None,
worker: WorkerConfig::default(),
storage: Some(StorageConfig::Noop),
@@ -180,14 +178,21 @@ impl BackendConfig {
#[derive(Debug, Default, Deserialize, Clone, Serialize)]
pub struct VerifMethodConfig {
- /// Verification method for Gmail emails.
- pub gmail: GmailVerifMethod,
- /// Verification method for Hotmail B2B emails.
- pub hotmailb2b: HotmailB2BVerifMethod,
- /// Verification method for Hotmail B2C emails.
- pub hotmailb2c: HotmailB2CVerifMethod,
- /// Verification method for Yahoo emails.
- pub yahoo: YahooVerifMethod,
+ pub proxies: HashMap<String, CheckEmailInputProxy>,
+ pub gmail: check_if_email_exists::smtp::verif_method::GmailVerifMethod,
+ pub hotmailb2b: check_if_email_exists::smtp::verif_method::HotmailB2BVerifMethod,
+ pub hotmailb2c: check_if_email_exists::smtp::verif_method::HotmailB2CVerifMethod,
+ pub yahoo: check_if_email_exists::smtp::verif_method::YahooVerifMethod,
+ pub everything_else: check_if_email_exists::smtp::verif_method::EverythingElseVerifMethod,
+}
+
+pub struct VerifMethodSmtpConfig {
+ pub from_email: Option<String>,
+ pub hello_name: Option<String>,
+ pub smtp_port: Option<u16>,
+ pub retries: Option<u8>,
+ pub proxy: Option<String>,
+ pub smtp_timeout: Option<Duration>,
}
#[derive(Debug, Default, Deserialize, Clone, Serialize)]
@@ -263,8 +268,11 @@ pub async fn load_config() -> Result<BackendConfig, anyhow::Error> {
.add_source(config::File::with_name("backend_config"))
.add_source(config::Environment::with_prefix("RCH").separator("__"));
- let cfg = cfg.build()?.try_deserialize::<BackendConfig>()?;
+ let mut cfg = cfg.build()?.try_deserialize::<BackendConfig>()?;
+ // Perform additional checks
+
+ // 1. Make sure that if the worker is enabled, a Postgres database is configured.
if cfg.worker.enable {
warn!(target: LOG_TARGET, "The worker feature is currently in beta. Please send any feedback to [email protected].");
@@ -274,13 +282,184 @@ pub async fn load_config() -> Result<BackendConfig, anyhow::Error> {
}
}
+ // 2. If the `proxy` field is set, move it to the `proxies` field with the
+ // "default" key.
+ #[allow(deprecated)]
+ if let Some(proxy) = cfg.proxy.take() {
+ cfg.verif_method
+ .proxies
+ .insert("default".to_string(), proxy);
+
+ cfg.proxy = None;
+ }
+
+ // 3. Validate the verif_method proxies, meaning that for each email
+ // provider's verification method, the proxy (if set) must exist in the
+ // `proxies` field.
+ cfg.verif_method.validate_proxies()?;
+
Ok(cfg)
}
#[cfg(test)]
mod tests {
use super::*;
- use std::env;
+ use check_if_email_exists::smtp::verif_method::{
+ EverythingElseVerifMethod, GmailVerifMethod, HotmailB2BVerifMethod, VerifMethodSmtpConfig,
+ };
+ use serial_test::serial;
+ use std::{env, time::Duration};
+
+ #[tokio::test]
+ #[serial]
+ async fn test_proxies() {
+ env::set_var("RCH__VERIF_METHOD__PROXIES__PROXY3__HOST", "test-proxy");
+ env::set_var("RCH__VERIF_METHOD__PROXIES__PROXY3__PORT", "1234");
+ let cfg = load_config().await.unwrap();
+ // Proxies
+ assert_eq!(cfg.verif_method.proxies.len(), 1);
+ assert_eq!(
+ cfg.verif_method.proxies.get("proxy3").unwrap().host,
+ "test-proxy"
+ );
+ assert_eq!(cfg.verif_method.proxies.get("proxy3").unwrap().port, 1234);
+
+ env::remove_var("RCH__VERIF_METHOD__PROXIES__PROXY3__HOST");
+ env::remove_var("RCH__VERIF_METHOD__PROXIES__PROXY3__PORT");
+ }
+
+ #[tokio::test]
+ #[serial]
+ async fn test_default_proxy() {
+ env::set_var("RCH__PROXY__HOST", "test-default-proxy");
+ env::set_var("RCH__PROXY__PORT", "5678");
+ let cfg = load_config().await.unwrap();
+ // Proxies
+ assert_eq!(cfg.verif_method.proxies.len(), 1);
+ assert_eq!(
+ cfg.verif_method.proxies.get("default").unwrap().host,
+ "test-default-proxy"
+ );
+ assert_eq!(cfg.verif_method.proxies.get("default").unwrap().port, 5678);
+
+ env::remove_var("RCH__PROXY__HOST");
+ env::remove_var("RCH__PROXY__PORT");
+ }
+
+ #[test]
+ fn test_deserialize_verif_method() {
+ let toml = r#"
+[proxies]
+# Allow inline
+proxy1 = { host = "my-proxy1", port = 1051, username = "user1", password = "pass1" }
+[proxies.proxy2]
+host = "my-proxy2"
+port = 1052
+username = "user2"
+password = "pass2"
+
+[hotmailb2c]
+type = "headless"
+
+[yahoo]
+type = "headless"
+
+[gmail]
+type = "smtp"
+from_email = "[email protected]"
+hello_name = "email.com"
+proxy = "proxy1"
+smtp_port = 465
+retries = 3
+smtp_timeout = { secs = 23, nanos = 0 }
+
+# Allow skipping internal fields
+[hotmailb2b]
+type = "smtp"
+
+# Allow skipping whole section
+# [everything_else.Smtp]
+"#;
+
+ let verif_method: VerifMethod = toml::from_str(toml).unwrap();
+ assert_eq!(verif_method.proxies.len(), 2);
+ assert_eq!(
+ verif_method.proxies.get("proxy1").unwrap().host,
+ "my-proxy1"
+ );
+ assert_eq!(verif_method.proxies.get("proxy1").unwrap().port, 1051);
+ assert_eq!(
+ verif_method
+ .proxies
+ .get("proxy1")
+ .unwrap()
+ .username
+ .as_deref(),
+ Some("user1")
+ );
+ assert_eq!(
+ verif_method
+ .proxies
+ .get("proxy1")
+ .unwrap()
+ .password
+ .as_deref(),
+ Some("pass1")
+ );
+
+ assert_eq!(
+ verif_method.proxies.get("proxy2").unwrap().host,
+ "my-proxy2"
+ );
+ assert_eq!(verif_method.proxies.get("proxy2").unwrap().port, 1052);
+ assert_eq!(
+ verif_method
+ .proxies
+ .get("proxy2")
+ .unwrap()
+ .username
+ .as_deref(),
+ Some("user2")
+ );
+ assert_eq!(
+ verif_method
+ .proxies
+ .get("proxy2")
+ .unwrap()
+ .password
+ .as_deref(),
+ Some("pass2")
+ );
+
+ assert_eq!(
+ verif_method.gmail,
+ GmailVerifMethod::Smtp(VerifMethodSmtpConfig {
+ from_email: "[email protected]".to_string(),
+ hello_name: "email.com".to_string(),
+ smtp_port: 465,
+ retries: 3,
+ proxy: Some("proxy1".to_string()),
+ smtp_timeout: Some(Duration::from_secs(23)),
+ })
+ );
+
+ assert_eq!(
+ verif_method.hotmailb2b,
+ HotmailB2BVerifMethod::Smtp(VerifMethodSmtpConfig {
+ from_email: "[email protected]".to_string(),
+ hello_name: "gmail.com".to_string(),
+ smtp_port: 25,
+ retries: 1,
+ proxy: None,
+ smtp_timeout: None,
+ })
+ );
+
+ assert_eq!(
+ verif_method.everything_else,
+ EverythingElseVerifMethod::Smtp(Default::default())
+ );
+ }
#[tokio::test]
async fn test_env_vars() {
diff --git a/backend/src/http/v0/bulk/post.rs b/backend/src/http/v0/bulk/post.rs
index 22e01777..b8bb108e 100644
--- a/backend/src/http/v0/bulk/post.rs
+++ b/backend/src/http/v0/bulk/post.rs
@@ -16,8 +16,7 @@
//! This file implements the `POST /v0/bulk` endpoint.
-use check_if_email_exists::CheckEmailInputProxy;
-use check_if_email_exists::LOG_TARGET;
+use check_if_email_exists::{CheckEmailInputProxy, LOG_TARGET};
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Postgres};
use std::sync::Arc;
diff --git a/backend/src/http/v0/bulk/task.rs b/backend/src/http/v0/bulk/task.rs
index 1b9a2bfe..ab0c698c 100644
--- a/backend/src/http/v0/bulk/task.rs
+++ b/backend/src/http/v0/bulk/task.rs
@@ -17,8 +17,10 @@
//! This file implements the `POST /bulk` endpoint.
use check_if_email_exists::{
- check_email, CheckEmailInput, CheckEmailInputBuilder, CheckEmailInputProxy, CheckEmailOutput,
- Reachable, LOG_TARGET,
+ check_email,
+ smtp::verif_method::{VerifMethod, VerifMethodSmtpConfig},
+ CheckEmailInput, CheckEmailInputBuilder, CheckEmailInputProxy, CheckEmailOutput, Reachable,
+ LOG_TARGET,
};
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Postgres};
@@ -63,22 +65,28 @@ impl Iterator for TaskInputIterator {
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.body.smtp_ports.len() {
- let mut item = CheckEmailInputBuilder::default();
- let mut item: &mut CheckEmailInputBuilder = item.to_email(self.body.to_email.clone());
-
- if let Some(name) = &self.body.hello_name {
- item = item.hello_name(name.clone());
- }
-
- if let Some(email) = &self.body.from_email {
- item = item.from_email(email.clone());
- }
-
- item = item.smtp_port(self.body.smtp_ports[self.index]);
+ let hello_name = self
+ .body
+ .hello_name
+ .clone()
+ .unwrap_or_else(|| VerifMethodSmtpConfig::default().hello_name);
+ let from_email = self
+ .body
+ .from_email
+ .clone()
+ .unwrap_or_else(|| VerifMethodSmtpConfig::default().from_email);
+
+ let verif_method = VerifMethod::new_with_same_config_for_all(
+ self.body.proxy.clone(),
+ hello_name,
+ from_email,
+ self.body.smtp_ports[self.index],
+ None,
+ 1,
+ );
- if let Some(proxy) = &self.body.proxy {
- item = item.proxy(Some(proxy.clone()));
- }
+ let mut item = CheckEmailInputBuilder::default();
+ let item: &mut CheckEmailInputBuilder = item.to_email(self.body.to_email.clone());
// Currently, for the legacy and deprecated /v0/bulk endpoints, we
// don't pass in a BackendConfig to the job. Therefore, we must create
@@ -89,6 +97,7 @@ impl Iterator for TaskInputIterator {
let sentry_dsn = env::var("RCH_SENTRY_DSN");
let webdriver_addr =
env::var("RCH_WEBDRIVER_ADDR").unwrap_or_else(|_| "http://localhost:9515".into());
+ item.verif_method(verif_method);
item.backend_name(backend_name);
item.sentry_dsn(sentry_dsn.ok());
item.webdriver_addr(webdriver_addr);
diff --git a/backend/src/http/v0/check_email/post.rs b/backend/src/http/v0/check_email/post.rs
index 4cb746a7..af399f55 100644
--- a/backend/src/http/v0/check_email/post.rs
+++ b/backend/src/http/v0/check_email/post.rs
@@ -16,13 +16,10 @@
//! This file implements the `POST /v0/check_email` endpoint.
-use check_if_email_exists::{
- check_email, CheckEmailInput, CheckEmailInputProxy, GmailVerifMethod, HotmailB2BVerifMethod,
- HotmailB2CVerifMethod, YahooVerifMethod, LOG_TARGET,
-};
+use check_if_email_exists::smtp::verif_method::VerifMethod;
+use check_if_email_exists::{check_email, CheckEmailInput, LOG_TARGET};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
-use std::time::Duration;
use warp::{http, Filter};
use crate::config::BackendConfig;
@@ -32,42 +29,19 @@ use crate::http::{check_header, ReacherResponseError};
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct CheckEmailRequest {
pub to_email: String,
- pub from_email: Option<String>,
- pub hello_name: Option<String>,
- pub gmail_verif_method: Option<GmailVerifMethod>,
- pub hotmailb2b_verif_method: Option<HotmailB2BVerifMethod>,
- pub hotmailb2c_verif_method: Option<HotmailB2CVerifMethod>,
- pub yahoo_verif_method: Option<YahooVerifMethod>,
- pub proxy: Option<CheckEmailInputProxy>,
- pub smtp_port: Option<u16>,
+ pub verif_method: Option<VerifMethod>,
}
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()),
- gmail_verif_method: self.gmail_verif_method.unwrap_or(config.verif_method.gmail),
- hotmailb2b_verif_method: self
- .hotmailb2b_verif_method
- .unwrap_or(config.verif_method.hotmailb2b),
- hotmailb2c_verif_method: self
- .hotmailb2c_verif_method
- .unwrap_or(config.verif_method.hotmailb2c),
- yahoo_verif_method: self.yahoo_verif_method.unwrap_or(config.verif_method.yahoo),
- proxy: self
- .proxy
- .as_ref()
- .or_else(|| config.proxy.as_ref())
- .cloned(),
- smtp_timeout: config.smtp_timeout.map(Duration::from_secs),
- smtp_port: self
- .smtp_port
- .unwrap_or_else(|| CheckEmailInput::default().smtp_port),
+ verif_method: self
+ .verif_method
+ .clone()
+ .unwrap_or(config.verif_method.clone()),
sentry_dsn: config.sentry_dsn.clone(),
backend_name: config.backend_name.clone(),
- retries: 2,
webdriver_config: config.webdriver.clone(),
..Default::default()
}
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
index a4c2c76c..03695314 100644
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "check-if-email-exists-cli"
-version = "0.10.2"
+version = "0.11.0"
default-run = "check_if_email_exists"
edition = "2018"
description = "Check if an email address exists without sending any email."
diff --git a/cli/src/main.rs b/cli/src/main.rs
index e68d643e..810cb43d 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -15,8 +15,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use check_if_email_exists::{
- check_email, CheckEmailInputBuilder, CheckEmailInputProxy, GmailVerifMethod,
- HotmailB2BVerifMethod, HotmailB2CVerifMethod, YahooVerifMethod,
+ check_email, smtp::verif_method::VerifMethod, CheckEmailInputBuilder, CheckEmailInputProxy,
};
use clap::Parser;
use once_cell::sync::Lazy;
@@ -56,22 +55,6 @@ pub struct Cli {
#[clap(long, env, default_value = "25")]
pub smtp_port: u16,
- /// Select how to verify Yahoo email addresses: api, headless or smtp.
- #[clap(long, env, default_value = "headless", parse(try_from_str))]
- pub yahoo_verif_method: YahooVerifMethod,
-
- /// Select how to verify Gmail email addresses: api or smtp.
- #[clap(long, env, default_value = "smtp", parse(try_from_str))]
- pub gmail_verif_method: GmailVerifMethod,
-
- /// Select how to verify Hotmail B2B email addresses: smtp.
- #[clap(long, env, default_value = "smtp", parse(try_from_str))]
- pub hotmailb2b_verif_method: HotmailB2BVerifMethod,
-
- /// Select how to verify Hotmail B2C email addresses: headless or smtp.
- #[clap(long, env, default_value = "headless", parse(try_from_str))]
- pub hotmailb2c_verif_method: HotmailB2CVerifMethod,
-
/// Whether to check if a gravatar image is existing for the given email.
#[clap(long, env, default_value = "false", parse(try_from_str))]
pub check_gravatar: bool,
@@ -93,30 +76,32 @@ async fn main() -> Result<(), anyhow::Error> {
let to_email = &CONF.to_email;
+ let proxy = CONF
+ .proxy_host
+ .as_ref()
+ .map(|proxy_host| CheckEmailInputProxy {
+ host: proxy_host.clone(),
+ port: CONF.proxy_port,
+ username: CONF.proxy_username.clone(),
+ password: CONF.proxy_password.clone(),
+ });
+ let verif_method = VerifMethod::new_with_same_config_for_all(
+ proxy,
+ CONF.from_email.clone(),
+ CONF.hello_name.clone(),
+ CONF.smtp_port,
+ None,
+ 1,
+ );
+
let mut input = CheckEmailInputBuilder::default();
- let mut input = input
+ let 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)
- .hotmailb2b_verif_method(CONF.hotmailb2b_verif_method)
- .hotmailb2c_verif_method(CONF.hotmailb2c_verif_method)
+ .verif_method(verif_method)
.check_gravatar(CONF.check_gravatar)
.haveibeenpwned_api_key(CONF.haveibeenpwned_api_key.clone())
.backend_name("reacher-cli".to_string())
- .retries(2);
-
- if let Some(proxy_host) = &CONF.proxy_host {
- 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()?;
+ .build()?;
let result = check_email(&input).await;
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 977a4a44..8a30a050 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "check-if-email-exists"
-version = "0.10.2"
+version = "0.11.0"
authors = ["Amaury <[email protected]>"]
categories = ["email"]
description = "Check if an email address exists without sending any email"
diff --git a/core/src/lib.rs b/core/src/lib.rs
index 587965f1..8772dc8b 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -35,22 +35,37 @@
//!
//! ```rust
//! use check_if_email_exists::{check_email, CheckEmailInputBuilder, CheckEmailInputProxy};
+//! use check_if_email_exists::smtp::verif_method::{VerifMethod, VerifMethodSmtpConfig, GmailVerifMethod};
+//! use std::collections::HashMap;
//!
//! async fn check() {
//! // Let's say we want to test the deliverability of [email protected].
+//!
+//! // We can tweak how we want to verify the email address, though using
+//! // the default values is usually enough. However, if you want to use a
+//! // proxy, you can do so like this:
+//! let mut proxies = HashMap::new();
+//! proxies.insert("proxy1".to_string(), CheckEmailInputProxy {
+//! host: "my-proxy.io".to_string(), // Use a SOCKS5 proxy to verify the email
+//! port: 1080,
+//! username: None, // You can also set it non-empty
+//! password: None
+//! });
+//! let verif_method = VerifMethod {
+//! proxies,
+//! gmail: GmailVerifMethod::Smtp(VerifMethodSmtpConfig {
+//! from_email: "[email protected]".to_string(), // Used in the `MAIL FROM:` command
+//! hello_name: "example.org".to_string(), // Used in the `EHLO` command
+//! smtp_port: 587, // Use port 587 instead of 25
+//! proxy: Some("proxy1".to_string()), // Use the proxy we defined above
+//! ..Default::default()
+//! }),
+//! ..Default::default()
+//! };
+//!
//! 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
-//! password: None
-//! }))
+//! .verif_method(verif_method)
//! .build()
//! .unwrap();
//!
@@ -256,7 +271,6 @@ pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput {
.as_ref()
.expect("We already checked that the email has valid format. qed."),
host.exchange(),
- input.smtp_port,
my_syntax.domain.as_ref(),
input,
)
diff --git a/core/src/misc/mod.rs b/core/src/misc/mod.rs
index c3ccc879..dad41abd 100644
--- a/core/src/misc/mod.rs
+++ b/core/src/misc/mod.rs
@@ -117,8 +117,8 @@ mod tests {
let misc_details = check_misc(&syntax, true, None).await;
- assert_eq!(misc_details.is_disposable, false); // gmail.com is not in mailchecker
- assert_eq!(misc_details.is_role_account, true); // test is in roles.txt
- assert_eq!(misc_details.is_b2c, true); // gmail.com is in b2c.txt
+ assert!(!misc_details.is_disposable); // gmail.com is not in mailchecker
+ assert!(misc_details.is_role_account); // test is in roles.txt
+ assert!(misc_details.is_b2c); // gmail.com is in b2c.txt
}
}
diff --git a/core/src/mx/mod.rs b/core/src/mx/mod.rs
index f044eee3..f3343c9c 100644
--- a/core/src/mx/mod.rs
+++ b/core/src/mx/mod.rs
@@ -109,3 +109,57 @@ pub async fn check_mx(syntax: &SyntaxDetails) -> Result<MxDetails, MxError> {
},
}
}
+
+/// Check if the MX host is from Google, i.e. either a @gmail.com address, or
+/// a Google Suite email.
+pub fn is_gmail(mx_host: &str) -> bool {
+ mx_host.to_lowercase().ends_with(".google.com.")
+}
+
+/// Check if a MX host is from outlook (includes @hotmail.*, @outlook.* and
+/// all Microsoft 365 addresses).
+///
+/// After some testing I got:
+/// After some testing, I got:
+/// - *@outlook.com -> `outlook-com.olc.protection.outlook.com.`
+/// - *@outlook.fr -> `eur.olc.protection.outlook.com.`
+/// - *@hotmail.com -> `hotmail-com.olc.protection.outlook.com.`
+/// - *@hotmail.fr -> `eur.olc.protection.outlook.com.`
+/// - *@hotmail.nl -> `eur.olc.protection.outlook.com.`
+///
+/// But Microsoft 365 (B2B) addresses end with "mail.protection.outlook.com."
+///
+/// TL;DR:
+/// - B2C emails -> end with ".olc.protection.outlook.com."
+/// - B2B emails -> end with ".mail.protection.outlook.com."
+pub fn is_hotmail(mx_host: &str) -> bool {
+ mx_host.to_lowercase().ends_with(".protection.outlook.com.")
+}
+
+/// Check if an address is a Hotmail B2B email address.
+pub fn is_hotmail_b2b(mx_host: &str) -> bool {
+ is_hotmail(mx_host) && !mx_host.ends_with(".olc.protection.outlook.com.")
+}
+
+/// Check if an address is a Hotmail B2C email address.
+pub fn is_hotmail_b2c(mx_host: &str) -> bool {
+ is_hotmail(mx_host) && mx_host.ends_with(".olc.protection.outlook.com.")
+}
+
+/// Check if the MX host is behind Mimecast.
+pub fn is_mimecast(mx_host: &str) -> bool {
+ mx_host.to_lowercase().ends_with(".mimecast.com.")
+}
+
+/// Check if the MX host is behind Proofpoint.
+pub fn is_proofpoint(mx_host: &str) -> bool {
+ mx_host.to_lowercase().ends_with(".pphosted.com.") || mx_host.ends_with("ppe-hosted.com.")
+}
+
+/// Check if the MX host is from Yahoo.
+/// Examples:
+/// - mta7.am0.yahoodns.net.
+/// - mx-eu.mail.am0.yahoodns.net.
+pub fn is_yahoo(mx_host: &str) -> bool {
+ mx_host.to_lowercase().ends_with(".yahoodns.net.")
+}
diff --git a/core/src/smtp/connect.rs b/core/src/smtp/connect.rs
index 60976606..38138a60 100644
--- a/core/src/smtp/connect.rs
+++ b/core/src/smtp/connect.rs
@@ -28,11 +28,9 @@ use tokio::io::{AsyncBufRead, AsyncRead, AsyncWrite, BufStream};
use tokio::net::TcpStream;
use super::parser;
+use super::verif_method::VerifMethodSmtp;
use super::{SmtpDetails, SmtpError};
-use crate::{
- rules::{has_rule, Rule},
- util::input_output::CheckEmailInput,
-};
+use crate::rules::{has_rule, Rule};
use crate::{EmailAddress, LOG_TARGET};
// Define a new trait that combines AsyncRead, AsyncWrite, and Unpin
@@ -45,8 +43,8 @@ macro_rules! try_smtp (
if let Err(err) = $res {
tracing::debug!(
target: LOG_TARGET,
- email=$to_email,
- host=$host,
+ email=$to_email.to_string(),
+ mx_host=$host,
port=$port,
error=?err,
"Closing connection due to error"
@@ -61,27 +59,27 @@ macro_rules! try_smtp (
/// Connect to an SMTP host and return the configured client transport.
async fn connect_to_smtp_host(
- host: &str,
- port: u16,
- input: &CheckEmailInput,
+ to_email: &EmailAddress,
+ mx_host: &str,
+ verif_method: &VerifMethodSmtp,
) -> Result<SmtpTransport<BufStream<Box<dyn AsyncReadWrite>>>, SmtpError> {
// hostname verification fails if it ends with '.', for example, using
// SOCKS5 proxies we can `io: incomplete` error.
- let clean_host = host.trim_end_matches('.').to_string();
+ let clean_host = mx_host.trim_end_matches('.').to_string();
let smtp_client = SmtpClient::new()
- .hello_name(ClientId::Domain(input.hello_name.clone()))
+ .hello_name(ClientId::Domain(verif_method.config.hello_name.to_string()))
// Sometimes, using socks5 proxy, we get an `io: incomplete` error
// when using pipelining and sending two consecutive RCPT TO commands.
.pipelining(false);
- let stream: BufStream<Box<dyn AsyncReadWrite>> = match &input.proxy {
+ let stream: BufStream<Box<dyn AsyncReadWrite>> = match &verif_method.proxy {
Some(proxy) => {
let socks_stream =
if let (Some(username), Some(password)) = (&proxy.username, &proxy.password) {
Socks5Stream::connect_with_password(
(proxy.host.as_ref(), proxy.port),
clean_host.clone(),
- port,
+ verif_method.config.smtp_port,
username.clone(),
password.clone(),
Config::default(),
@@ -91,7 +89,7 @@ async fn connect_to_smtp_host(
Socks5Stream::connect(
(proxy.host.as_ref(), proxy.port),
clean_host.clone(),
- port,
+ verif_method.config.smtp_port,
Config::default(),
)
.await?
@@ -99,7 +97,9 @@ async fn connect_to_smtp_host(
BufStream::new(Box::new(socks_stream) as Box<dyn AsyncReadWrite>)
}
None => {
- let tcp_stream = TcpStream::connect(format!("{}:{}", clean_host, port)).await?;
+ let tcp_stream =
+ TcpStream::connect(format!("{}:{}", clean_host, verif_method.config.smtp_port))
+ .await?;
BufStream::new(Box::new(tcp_stream) as Box<dyn AsyncReadWrite>)
}
};
@@ -107,10 +107,10 @@ async fn connect_to_smtp_host(
let mut smtp_transport = SmtpTransport::new(smtp_client, stream).await?;
// Set "MAIL FROM"
- let from_email = EmailAddress::from_str(&input.from_email).unwrap_or_else(|_| {
+ let from_email = EmailAddress::from_str(&verif_method.config.from_email).unwrap_or_else(|_| {
tracing::warn!(
target: LOG_TARGET,
- from_email=input.from_email,
+ from_email=verif_method.config.from_email,
"Invalid 'from_email' provided, using default: '[email protected]'"
);
EmailAddress::from_str("[email protected]").expect("Default email is valid")
@@ -121,9 +121,9 @@ async fn connect_to_smtp_host(
.command(MailCommand::new(Some(from_email.into_inner()), vec![]))
.await,
smtp_transport,
- input.to_email,
+ to_email,
clean_host,
- port
+ verif_method.config.smtp_port
);
Ok(smtp_transport)
@@ -222,12 +222,12 @@ async fn smtp_is_catch_all<S: AsyncBufRead + AsyncWrite + Unpin + Send>(
smtp_transport: &mut SmtpTransport<S>,
domain: &str,
host: &str,
- input: &CheckEmailInput,
+ to_email: &EmailAddress,
) -> Result<bool, SmtpError> {
if has_rule(domain, host, &Rule::SkipCatchAll) {
tracing::debug!(
target: LOG_TARGET,
- email=input.to_email,
+ email=to_email.to_string(),
domain=domain,
"Skipping catch-all check"
);
@@ -250,16 +250,15 @@ async fn smtp_is_catch_all<S: AsyncBufRead + AsyncWrite + Unpin + Send>(
/// Creates an SMTP future for email verification.
async fn create_smtp_future(
to_email: &EmailAddress,
- host: &str,
- port: u16,
+ mx_host: &str,
domain: &str,
- input: &CheckEmailInput,
+ verif_method: &VerifMethodSmtp,
) -> Result<(bool, Deliverability), SmtpError> {
// FIXME If the SMTP is not connectable, we should actually return an
// Ok(SmtpDetails { can_connect_smtp: false, ... }).
- let mut smtp_transport = connect_to_smtp_host(host, port, input).await?;
+ let mut smtp_transport = connect_to_smtp_host(to_email, mx_host, verif_method).await?;
- let is_catch_all = smtp_is_catch_all(&mut smtp_transport, domain, host, input)
+ let is_catch_all = smtp_is_catch_all(&mut smtp_transport, domain, mx_host, to_email)
.await
.unwrap_or(false);
let deliverability = if is_catch_all {
@@ -281,13 +280,13 @@ async fn create_smtp_future(
if parser::is_err_io_errors(e) {
tracing::debug!(
target: LOG_TARGET,
- email=input.to_email,
+ email=to_email.to_string(),
error=?e,
"Got `io: incomplete` error, reconnecting"
);
let _ = smtp_transport.quit().await;
- smtp_transport = connect_to_smtp_host(host, port, input).await?;
+ smtp_transport = connect_to_smtp_host(to_email, mx_host, verif_method).await?;
result = check_email_deliverability(&mut smtp_transport, to_email).await;
}
}
@@ -307,14 +306,13 @@ async fn create_smtp_future(
/// retries.
async fn check_smtp_without_retry(
to_email: &EmailAddress,
- host: &str,
- port: u16,
+ mx_host: &str,
domain: &str,
- input: &CheckEmailInput,
+ verif_method: &VerifMethodSmtp,
) -> Result<SmtpDetails, SmtpError> {
- let fut = create_smtp_future(to_email, host, port, domain, input);
+ let fut = create_smtp_future(to_email, mx_host, domain, verif_method);
- let (is_catch_all, deliverability) = match input.smtp_timeout {
+ let (is_catch_all, deliverability) = match verif_method.config.smtp_timeout {
Some(smtp_timeout) => {
let timeout = tokio::time::timeout(smtp_timeout, fut);
@@ -340,29 +338,30 @@ async fn check_smtp_without_retry(
#[async_recursion]
pub async fn check_smtp_with_retry(
to_email: &EmailAddress,
- host: &str,
- port: u16,
+ mx_host: &str,
domain: &str,
- input: &CheckEmailInput,
+ verif_method: &VerifMethodSmtp,
+ // Number of remaining retries.
count: usize,
) -> Result<SmtpDetails, SmtpError> {
tracing::debug!(
target: LOG_TARGET,
- email=input.to_email,
- attempt=input.retries - count + 1,
- host=host,
- port=port,
+ email=to_email.to_string(),
+ attempt=verif_method.config.retries - count + 1,
+ mx_host=mx_host,
+ port=verif_method.config.smtp_port,
+ using_proxy=verif_method.proxy.is_some(),
"Check SMTP"
);
- let result = check_smtp_without_retry(to_email, host, port, domain, input).await;
+ let result = check_smtp_without_retry(to_email, mx_host, domain, verif_method).await;
tracing::debug!(
target: LOG_TARGET,
- email=input.to_email,
- attempt=input.retries - count + 1,
- host=host,
- port=port,
+ email=to_email.to_string(),
+ attempt=verif_method.config.retries - count + 1,
+ mx_host=mx_host,
+ port=verif_method.config.smtp_port,
result=?result,
"Got SMTP check result"
);
@@ -381,10 +380,10 @@ pub async fn check_smtp_with_retry(
} else {
tracing::debug!(
target: LOG_TARGET,
- email=input.to_email,
+ email=to_email.to_string(),
"Potential greylisting detected, retrying"
);
- check_smtp_with_retry(to_email, host, port, domain, input, count - 1).await
+ check_smtp_with_retry(to_email, mx_host, domain, verif_method, count - 1).await
}
}
_ => result,
diff --git a/core/src/smtp/gmail.rs b/core/src/smtp/gmail.rs
index bd95d6d3..7ba556a9 100644
--- a/core/src/smtp/gmail.rs
+++ b/core/src/smtp/gmail.rs
@@ -42,8 +42,13 @@ impl From<ReqwestError> for GmailError {
}
}
+#[allow(dead_code)]
/// Use HTTP request to verify if a Gmail email address exists.
/// See: <https://blog.0day.rocks/abusing-gmail-to-get-previously-unlisted-e-mail-addresses-41544b62b2>
+///
+/// This method doesn't work anymore, as Google has patched the vulnerability,
+/// but it's kept here for historical reasons.
+#[deprecated]
pub async fn check_gmail_via_api(
to_email: &EmailAddress,
input: &CheckEmailInput,
@@ -70,12 +75,6 @@ pub async fn check_gmail_via_api(
})
}
-/// Check if the MX host is from Google, i.e. either a @gmail.com address, or
-/// a Google Suite email.
-pub fn is_gmail(host: &str) -> bool {
- host.to_lowercase().ends_with(".google.com.")
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -91,6 +90,7 @@ mod tests {
.build()
.unwrap();
+ #[allow(deprecated)]
let smtp_details = check_gmail_via_api(&to_email, &input).await;
assert!(smtp_details.is_ok());
diff --git a/core/src/smtp/http_api.rs b/core/src/smtp/http_api.rs
index 97d6b000..ffee2152 100644
--- a/core/src/smtp/http_api.rs
+++ b/core/src/smtp/http_api.rs
@@ -15,38 +15,13 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::util::input_output::CheckEmailInput;
-use crate::LOG_TARGET;
use reqwest::Error as ReqwestError;
/// Helper function to create a reqwest client, with optional proxy.
pub fn create_client(
- input: &CheckEmailInput,
- api_name: &str,
+ _input: &CheckEmailInput,
+ _api_name: &str,
) -> Result<reqwest::Client, ReqwestError> {
- if let Some(proxy) = &input.proxy {
- tracing::debug!(
- target: LOG_TARGET,
- email=input.to_email,
- proxy_host=proxy.host,
- proxy_port=proxy.port,
- api=api_name,
- "Using proxy for API request"
- );
-
- let proxy = if proxy.username.is_some() && proxy.password.is_some() {
- reqwest::Proxy::all(format!(
- "socks5://{}:{}@{}:{}",
- proxy.username.as_ref().unwrap(),
- proxy.password.as_ref().unwrap(),
- proxy.host,
- proxy.port
- ))?
- } else {
- reqwest::Proxy::all(format!("socks5://{}:{}", proxy.host, proxy.port))?
- };
-
- reqwest::Client::builder().proxy(proxy).build()
- } else {
- Ok(reqwest::Client::new())
- }
+ // TODO: Allow proxying for HTTP API requests.
+ Ok(reqwest::Client::new())
}
diff --git a/core/src/smtp/mod.rs b/core/src/smtp/mod.rs
index b5ccbf4f..fe150b93 100644
--- a/core/src/smtp/mod.rs
+++ b/core/src/smtp/mod.rs
@@ -17,44 +17,40 @@
mod connect;
mod error;
mod gmail;
-
mod headless;
mod http_api;
mod outlook;
mod parser;
+pub mod verif_method;
mod yahoo;
+use crate::util::input_output::CheckEmailInput;
use crate::EmailAddress;
-use crate::{
- util::input_output::CheckEmailInput, GmailVerifMethod, HotmailB2CVerifMethod, YahooVerifMethod,
-};
use connect::check_smtp_with_retry;
use hickory_proto::rr::Name;
use serde::{Deserialize, Serialize};
use std::default::Default;
-
-pub use self::{
- gmail::is_gmail,
- outlook::{is_hotmail, is_hotmail_b2b, is_hotmail_b2c},
- yahoo::is_yahoo,
+use verif_method::{
+ EmailProvider, EverythingElseVerifMethod, GmailVerifMethod, HotmailB2BVerifMethod,
+ HotmailB2CVerifMethod, VerifMethodSmtp, YahooVerifMethod,
};
+
+pub use crate::mx::{is_gmail, is_hotmail, is_hotmail_b2b, is_hotmail_b2c, is_yahoo};
pub use error::*;
-#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
-pub struct SmtpConnection {
+#[derive(Debug, Deserialize, Serialize)]
+pub struct SmtpDebugVerifMethodSmtp {
/// The host we connected to via SMTP.
pub host: String,
- /// The port we connected to via SMTP.
- pub port: u16,
- /// Whether we used a proxy for the SMTP connection.
- pub used_proxy: bool,
+ /// The verification method used for the verification.
+ pub verif_method: VerifMethodSmtp,
}
-#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(tag = "type")]
-pub enum VerifMethod {
+pub enum SmtpDebugVerifMethod {
/// Email verification was done via SMTP.
- Smtp(SmtpConnection),
+ Smtp(SmtpDebugVerifMethodSmtp),
/// Email verification was done via an HTTP API.
Api,
/// Email verification was done via a headless browser.
@@ -79,10 +75,11 @@ pub struct SmtpDetails {
pub is_disabled: bool,
}
+/// Debug information on how the SMTP verification went.
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct SmtpDebug {
/// The verification method used for the email.
- pub verif_method: VerifMethod,
+ pub verif_method: SmtpDebugVerifMethod,
}
/// Get all email details we can from one single `EmailAddress`, without
@@ -90,48 +87,41 @@ pub struct SmtpDebug {
pub async fn check_smtp(
to_email: &EmailAddress,
host: &Name,
- port: u16,
domain: &str,
input: &CheckEmailInput,
) -> (Result<SmtpDetails, SmtpError>, SmtpDebug) {
let host_str = host.to_string();
let to_email_str = to_email.to_string();
+ let email_provider = EmailProvider::from_mx_host(&host_str);
- if is_hotmail_b2c(&host_str) {
- if let HotmailB2CVerifMethod::Headless = &input.hotmailb2c_verif_method {
- return (
- outlook::headless::check_password_recovery(
- &to_email_str,
- &input.webdriver_addr,
- &input.webdriver_config,
- )
- .await
- .map_err(Into::into),
- SmtpDebug {
- verif_method: VerifMethod::Headless,
- },
- );
- }
- } else if is_gmail(&host_str) {
- if let GmailVerifMethod::Api = &input.gmail_verif_method {
- return (
- gmail::check_gmail_via_api(to_email, input)
+ // Handle all non-SMTP verifications first, and return early. For the rest,
+ // we'll use SMTP, and return the config.
+ let smtp_verif_method_config = match &email_provider {
+ EmailProvider::HotmailB2C => match &input.verif_method.hotmailb2c {
+ HotmailB2CVerifMethod::Headless => {
+ return (
+ outlook::headless::check_password_recovery(
+ &to_email_str,
+ &input.webdriver_addr,
+ &input.webdriver_config,
+ )
.await
.map_err(Into::into),
- SmtpDebug {
- verif_method: VerifMethod::Api,
- },
- );
- }
- } else if is_yahoo(&host_str) {
- match &input.yahoo_verif_method {
+ SmtpDebug {
+ verif_method: SmtpDebugVerifMethod::Headless,
+ },
+ );
+ }
+ HotmailB2CVerifMethod::Smtp(c) => c,
+ },
+ EmailProvider::Yahoo => match &input.verif_method.yahoo {
YahooVerifMethod::Api => {
return (
yahoo::check_api(&to_email_str, input)
.await
.map_err(Into::into),
SmtpDebug {
- verif_method: VerifMethod::Api,
+ verif_method: SmtpDebugVerifMethod::Api,
},
);
}
@@ -145,21 +135,48 @@ pub async fn check_smtp(
.await
.map_err(Into::into),
SmtpDebug {
- verif_method: VerifMethod::Headless,
+ verif_method: SmtpDebugVerifMethod::Headless,
},
);
}
- _ => {} // For everything else, we use SMTP
- }
- }
+ YahooVerifMethod::Smtp(c) => c,
+ },
+ EmailProvider::Gmail => match &input.verif_method.gmail {
+ GmailVerifMethod::Smtp(c) => c,
+ },
+ EmailProvider::HotmailB2B => match &input.verif_method.hotmailb2b {
+ HotmailB2BVerifMethod::Smtp(c) => c,
+ },
+ EmailProvider::Mimecast => match &input.verif_method.mimecast {
+ verif_method::MimecastVerifMethod::Smtp(c) => c,
+ },
+ EmailProvider::Proofpoint => match &input.verif_method.proofpoint {
+ verif_method::ProofpointVerifMethod::Smtp(c) => c,
+ },
+ EmailProvider::EverythingElse => match &input.verif_method.everything_else {
+ EverythingElseVerifMethod::Smtp(c) => c,
+ },
+ };
+
+ // TODO: There's surely a way to not clone here.
+ let verif_method = VerifMethodSmtp::new(
+ smtp_verif_method_config.clone(),
+ input.verif_method.get_proxy(email_provider).cloned(),
+ );
(
- check_smtp_with_retry(to_email, &host_str, port, domain, input, input.retries).await,
+ check_smtp_with_retry(
+ to_email,
+ &host_str,
+ domain,
+ &verif_method,
+ verif_method.config.retries,
+ )
+ .await,
SmtpDebug {
- verif_method: VerifMethod::Smtp(SmtpConnection {
+ verif_method: SmtpDebugVerifMethod::Smtp(SmtpDebugVerifMethodSmtp {
host: host_str,
- port,
- used_proxy: input.proxy.is_some(),
+ verif_method,
}),
},
)
@@ -167,7 +184,10 @@ pub async fn check_smtp(
#[cfg(test)]
mod tests {
- use super::{check_smtp, SmtpConnection, SmtpError};
+ use super::*;
+ use crate::smtp::verif_method::GmailVerifMethod;
+ use crate::smtp::verif_method::VerifMethod;
+ use crate::smtp::verif_method::VerifMethodSmtpConfig;
use crate::CheckEmailInputBuilder;
use crate::EmailAddress;
use hickory_proto::rr::Name;
@@ -182,21 +202,32 @@ mod tests {
let host = Name::from_str("alt4.aspmx.l.google.com.").unwrap();
let input = CheckEmailInputBuilder::default()
.to_email("[email protected]".into())
- .gmail_verif_method(crate::GmailVerifMethod::Smtp)
- .smtp_timeout(Some(Duration::from_millis(1)))
+ .verif_method(VerifMethod {
+ gmail: GmailVerifMethod::Smtp(VerifMethodSmtpConfig {
+ smtp_timeout: Some(Duration::from_millis(1)),
+ retries: 1,
+ ..Default::default()
+ }),
+ ..Default::default()
+ })
.build()
.unwrap();
- let (res, smtp_debug) =
- runtime.block_on(check_smtp(&to_email, &host, 25, "gmail.com", &input));
- assert_eq!(
- smtp_debug.verif_method,
- super::VerifMethod::Smtp(SmtpConnection {
- host: host.to_string(),
- port: 25,
- used_proxy: input.proxy.is_some(),
- })
- );
+ let (res, smtp_debug) = runtime.block_on(check_smtp(&to_email, &host, "gmail.com", &input));
+ match smtp_debug.verif_method {
+ SmtpDebugVerifMethod::Smtp(SmtpDebugVerifMethodSmtp { host, verif_method }) => {
+ assert_eq!(host, "alt4.aspmx.l.google.com.");
+ assert_eq!(verif_method.config.smtp_port, 25);
+ assert_eq!(
+ verif_method.config.smtp_timeout,
+ Some(Duration::from_millis(1))
+ );
+ assert_eq!(verif_method.config.retries, 1);
+ assert_eq!(verif_method.proxy, None);
+ }
+ _ => panic!("Expected SmtpDebugVerifMethod::Smtp"),
+ }
+
match res {
Err(SmtpError::Timeout(_)) => (), // ErrorKind == Timeout
_ => panic!("check_smtp did not time out"),
diff --git a/core/src/smtp/outlook/mod.rs b/core/src/smtp/outlook/mod.rs
index 5d3386c0..a51b37f1 100644
--- a/core/src/smtp/outlook/mod.rs
+++ b/core/src/smtp/outlook/mod.rs
@@ -1,32 +1,2 @@
pub mod headless;
pub mod microsoft365;
-
-/// Check if a MX host is from outlook (includes @hotmail.*, @outlook.* and
-/// all Microsoft 365 addresses).
-///
-/// After some testing I got:
-/// After some testing, I got:
-/// - *@outlook.com -> `outlook-com.olc.protection.outlook.com.`
-/// - *@outlook.fr -> `eur.olc.protection.outlook.com.`
-/// - *@hotmail.com -> `hotmail-com.olc.protection.outlook.com.`
-/// - *@hotmail.fr -> `eur.olc.protection.outlook.com.`
-/// - *@hotmail.nl -> `eur.olc.protection.outlook.com.`
-///
-/// But Microsoft 365 (B2B) addresses end with "mail.protection.outlook.com."
-///
-/// TL;DR:
-/// - B2C emails -> end with ".olc.protection.outlook.com."
-/// - B2B emails -> end with ".mail.protection.outlook.com."
-pub fn is_hotmail(host: &str) -> bool {
- host.to_lowercase().ends_with(".protection.outlook.com.")
-}
-
-/// Check if an address is a Hotmail B2B email address.
-pub fn is_hotmail_b2b(host: &str) -> bool {
- is_hotmail(host) && !host.ends_with(".olc.protection.outlook.com.")
-}
-
-/// Check if an address is a Hotmail B2C email address.
-pub fn is_hotmail_b2c(host: &str) -> bool {
- is_hotmail(host) && host.ends_with(".olc.protection.outlook.com.")
-}
diff --git a/core/src/smtp/verif_method.rs b/core/src/smtp/verif_method.rs
new file mode 100644
index 00000000..afaedd17
--- /dev/null
+++ b/core/src/smtp/verif_method.rs
@@ -0,0 +1,527 @@
+// check-if-email-exists
+// 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/>.
+
+//! TODO: This will ultimately be moved to core.
+
+use std::{collections::HashMap, time::Duration};
+
+use crate::{
+ mx::{is_mimecast, is_proofpoint},
+ util::input_output::CheckEmailInputProxy,
+};
+use serde::{Deserialize, Serialize};
+
+use super::{is_gmail, is_hotmail_b2b, is_hotmail_b2c, is_yahoo};
+
+#[derive(Debug, thiserror::Error)]
+pub enum VerifMethodError {
+ #[error("Invalid proxies: {0}")]
+ InvalidProxies(String),
+}
+
+/// Reacher categorizes each email into one of the following email providers.
+/// This is used to determine the verification method to use for each email
+/// provider.
+pub enum EmailProvider {
+ Gmail,
+ HotmailB2B,
+ HotmailB2C,
+ Proofpoint,
+ Mimecast,
+ Yahoo,
+ EverythingElse,
+}
+
+impl EmailProvider {
+ /// Determine the email provider from the MX host.
+ pub fn from_mx_host(host: &str) -> Self {
+ if is_hotmail_b2c(host) {
+ EmailProvider::HotmailB2C
+ } else if is_hotmail_b2b(host) {
+ EmailProvider::HotmailB2B
+ } else if is_gmail(host) {
+ EmailProvider::Gmail
+ } else if is_yahoo(host) {
+ EmailProvider::Yahoo
+ } else if is_proofpoint(host) {
+ EmailProvider::Proofpoint
+ } else if is_mimecast(host) {
+ EmailProvider::Mimecast
+ } else {
+ EmailProvider::EverythingElse
+ }
+ }
+}
+
+type ProxyID = String;
+
+/// The verification method to use for each email provider.
+#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
+#[serde(default)]
+pub struct VerifMethod {
+ /// Proxies to use for email verification. The key is any unique name for
+ /// the proxy, and the value is the proxy itself. For names, we recommend
+ /// "proxy1", "proxy2", etc.
+ pub proxies: HashMap<ProxyID, CheckEmailInputProxy>,
+ /// Verification method for Gmail.
+ pub gmail: GmailVerifMethod,
+ /// Verification method for Hotmail B2B.
+ pub hotmailb2b: HotmailB2BVerifMethod,
+ /// Verification method for Hotmail B2C.
+ pub hotmailb2c: HotmailB2CVerifMethod,
+ /// Verification method for Mimecast.
+ pub mimecast: MimecastVerifMethod,
+ /// Verification method for Proofpoint.
+ pub proofpoint: ProofpointVerifMethod,
+ /// Verification method for Yahoo.
+ pub yahoo: YahooVerifMethod,
+ /// Verification method for everything else.
+ pub everything_else: EverythingElseVerifMethod,
+}
+
+impl VerifMethod {
+ /// Create a new `VerifMethod` with the same configuration for all email
+ /// providers.
+ pub fn new_with_same_config_for_all(
+ proxy: Option<CheckEmailInputProxy>,
+ hello_name: String,
+ from_email: String,
+ smtp_port: u16,
+ smtp_timeout: Option<Duration>,
+ retries: usize,
+ ) -> Self {
+ let mut proxies = HashMap::new();
+ let proxy_id = if let Some(proxy) = proxy {
+ let proxy_id = "default".to_string();
+ proxies.insert(proxy_id.clone(), proxy);
+ Some(proxy_id)
+ } else {
+ None
+ };
+
+ Self {
+ proxies,
+ gmail: GmailVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: proxy_id.clone(),
+ hello_name: hello_name.clone(),
+ from_email: from_email.clone(),
+ smtp_port,
+ smtp_timeout,
+ retries,
+ }),
+ hotmailb2b: HotmailB2BVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: proxy_id.clone(),
+ hello_name: hello_name.clone(),
+ from_email: from_email.clone(),
+ smtp_port,
+ smtp_timeout,
+ retries,
+ }),
+ mimecast: MimecastVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: proxy_id.clone(),
+ hello_name: hello_name.clone(),
+ from_email: from_email.clone(),
+ smtp_port,
+ smtp_timeout,
+ retries,
+ }),
+ proofpoint: ProofpointVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: proxy_id.clone(),
+ hello_name: hello_name.clone(),
+ from_email: from_email.clone(),
+ smtp_port,
+ smtp_timeout,
+ retries,
+ }),
+ everything_else: EverythingElseVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: proxy_id,
+ hello_name,
+ from_email,
+ smtp_port,
+ smtp_timeout,
+ retries,
+ }),
+ ..Default::default()
+ }
+ }
+
+ pub fn validate_proxies(&self) -> Result<(), VerifMethodError> {
+ match &self.gmail {
+ GmailVerifMethod::Smtp(c) => {
+ if let Some(proxy_id) = &c.proxy {
+ self.proxies.get(proxy_id).ok_or_else(|| {
+ VerifMethodError::InvalidProxies(format!("Invalid Gmail proxy {proxy_id}"))
+ })?;
+ }
+ }
+ };
+
+ match &self.hotmailb2b {
+ HotmailB2BVerifMethod::Smtp(c) => {
+ if let Some(proxy_id) = &c.proxy {
+ self.proxies.get(proxy_id).ok_or_else(|| {
+ VerifMethodError::InvalidProxies(format!(
+ "Invalid Hotmail B2B proxy {proxy_id}"
+ ))
+ })?;
+ }
+ }
+ };
+
+ if let HotmailB2CVerifMethod::Smtp(c) = &self.hotmailb2c {
+ if let Some(proxy_id) = &c.proxy {
+ self.proxies.get(proxy_id).ok_or_else(|| {
+ VerifMethodError::InvalidProxies(format!(
+ "Invalid Hotmail B2C proxy {proxy_id}"
+ ))
+ })?;
+ }
+ };
+
+ if let YahooVerifMethod::Smtp(c) = &self.yahoo {
+ if let Some(proxy_id) = &c.proxy {
+ self.proxies.get(proxy_id).ok_or_else(|| {
+ VerifMethodError::InvalidProxies(format!("Invalid Yahoo proxy {proxy_id}"))
+ })?;
+ }
+ };
+
+ match &self.everything_else {
+ EverythingElseVerifMethod::Smtp(c) => {
+ if let Some(proxy_id) = &c.proxy {
+ self.proxies.get(proxy_id).ok_or_else(|| {
+ VerifMethodError::InvalidProxies(format!(
+ "Invalid EverythingElse proxy {proxy_id}"
+ ))
+ })?;
+ }
+ }
+ };
+
+ Ok(())
+ }
+
+ /// Get the proxy to use for the email provider. If there is a
+ /// configuration error, such as an unconfigured proxy, this will return
+ /// an error.
+ pub fn get_proxy(&self, email_provider: EmailProvider) -> Option<&CheckEmailInputProxy> {
+ match email_provider {
+ EmailProvider::Gmail => match &self.gmail {
+ GmailVerifMethod::Smtp(c) => c
+ .proxy
+ .as_ref()
+ .and_then(|proxy_id| self.proxies.get(proxy_id)),
+ },
+ EmailProvider::HotmailB2B => match &self.hotmailb2b {
+ HotmailB2BVerifMethod::Smtp(c) => c
+ .proxy
+ .as_ref()
+ .and_then(|proxy_id| self.proxies.get(proxy_id)),
+ },
+ EmailProvider::HotmailB2C => match &self.hotmailb2c {
+ HotmailB2CVerifMethod::Smtp(c) => c
+ .proxy
+ .as_ref()
+ .and_then(|proxy_id| self.proxies.get(proxy_id)),
+ _ => None,
+ },
+ EmailProvider::Mimecast => match &self.mimecast {
+ MimecastVerifMethod::Smtp(c) => c
+ .proxy
+ .as_ref()
+ .and_then(|proxy_id| self.proxies.get(proxy_id)),
+ },
+ EmailProvider::Proofpoint => match &self.proofpoint {
+ ProofpointVerifMethod::Smtp(c) => c
+ .proxy
+ .as_ref()
+ .and_then(|proxy_id| self.proxies.get(proxy_id)),
+ },
+ EmailProvider::Yahoo => match &self.yahoo {
+ YahooVerifMethod::Smtp(c) => c
+ .proxy
+ .as_ref()
+ .and_then(|proxy_id| self.proxies.get(proxy_id)),
+ _ => None,
+ },
+ EmailProvider::EverythingElse => match &self.everything_else {
+ EverythingElseVerifMethod::Smtp(c) => c
+ .proxy
+ .as_ref()
+ .and_then(|proxy_id| self.proxies.get(proxy_id)),
+ },
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum GmailVerifMethod {
+ Smtp(VerifMethodSmtpConfig),
+}
+
+impl Default for GmailVerifMethod {
+ fn default() -> Self {
+ GmailVerifMethod::Smtp(VerifMethodSmtpConfig::default())
+ }
+}
+
+#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum HotmailB2BVerifMethod {
+ /// Use Hotmail's SMTP servers to check if an email exists.
+ Smtp(VerifMethodSmtpConfig),
+}
+
+impl Default for HotmailB2BVerifMethod {
+ fn default() -> Self {
+ HotmailB2BVerifMethod::Smtp(VerifMethodSmtpConfig::default())
+ }
+}
+
+#[derive(Debug, Default, Deserialize, Clone, PartialEq, Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum HotmailB2CVerifMethod {
+ /// Use Hotmail's password recovery page to check if an email exists.
+ ///
+ /// This assumes you have a WebDriver compatible process running, then pass
+ /// its endpoint, usually http://localhost:9515, into the environment
+ /// variable RCH_WEBDRIVER_ADDR. We recommend running chromedriver (and not
+ /// geckodriver) as it allows parallel requests.
+ #[default]
+ Headless,
+ /// Use Hotmail's SMTP servers to check if an email exists.
+ Smtp(VerifMethodSmtpConfig),
+}
+
+#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum MimecastVerifMethod {
+ /// Use Mimecast's SMTP servers to check if an email exists.
+ Smtp(VerifMethodSmtpConfig),
+}
+
+impl Default for MimecastVerifMethod {
+ fn default() -> Self {
+ MimecastVerifMethod::Smtp(VerifMethodSmtpConfig::default())
+ }
+}
+
+#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum ProofpointVerifMethod {
+ /// Use Proofpoint's SMTP servers to check if an email exists.
+ Smtp(VerifMethodSmtpConfig),
+}
+
+impl Default for ProofpointVerifMethod {
+ fn default() -> Self {
+ ProofpointVerifMethod::Smtp(VerifMethodSmtpConfig::default())
+ }
+}
+
+#[derive(Debug, Default, Deserialize, Clone, PartialEq, Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum YahooVerifMethod {
+ /// Use Yahoo's API to check if an email exists.
+ Api,
+ /// Use Yahoo's password recovery page to check if an email exists.
+ ///
+ /// This assumes you have a WebDriver compatible process running, then pass
+ /// its endpoint, usually http://localhost:9515, into the environment
+ /// variable RCH_WEBDRIVER_ADDR. We recommend running chromedriver (and not
+ /// geckodriver) as it allows parallel requests.
+ #[default]
+ Headless,
+ /// Use Yahoo's SMTP servers to check if an email exists.
+ Smtp(VerifMethodSmtpConfig),
+}
+
+#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum EverythingElseVerifMethod {
+ /// Use the SMTP server of the email provider to check if an email exists.
+ Smtp(VerifMethodSmtpConfig),
+}
+
+impl Default for EverythingElseVerifMethod {
+ fn default() -> Self {
+ EverythingElseVerifMethod::Smtp(VerifMethodSmtpConfig::default())
+ }
+}
+
+/// Configuration on the SMTP verification method. If it used mostly as a
+/// serializable struct, to be converted into the domain type
+/// `VerifMethodSmtp`.
+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
+#[serde(default)]
+pub struct VerifMethodSmtpConfig {
+ /// Email to use in the `MAIL FROM:` SMTP command.
+ ///
+ /// Defaults to "[email protected]", which is an unused addressed
+ /// owned by Reacher.
+ ///
+ pub from_email: String,
+ /// Name to use in the `EHLO:` SMTP command.
+ ///
+ /// Defaults to "gmail.com" (note: "localhost" is not a FQDN), mostly for
+ /// testing purposes. You should set this to a domain you own.
+ pub hello_name: String,
+ /// Use a proxy to check if an email exists. This proxy must exist in the
+ /// `VerifMethod.proxies` field, and it must be a SOCKS5 proxy.
+ pub proxy: Option<ProxyID>,
+ /// SMTP port to use for email validation. Generally, ports 25, 465, 587
+ /// and 2525 are used.
+ ///
+ /// Defaults to 25.
+ pub smtp_port: u16,
+ /// Add timeout for the SMTP verification step. Set to None if you don't
+ /// want to use a timeout. This timeout is per SMTP connection. For
+ /// instance, if you set the number of retries to 2, then the total time
+ /// for the SMTP verification step can be up to 2 * `smtp_timeout`.
+ ///
+ /// Defaults to None.
+ pub smtp_timeout: Option<Duration>,
+ /// Number of total SMTP connections to do. Setting to 2 might bypass
+ /// greylisting on some servers, but takes more time.
+ ///
+ /// This setting's naming is a bit misleading, as it's not really retries,
+ /// but the total number of SMTP connections to do.
+ ///
+ /// Defaults to 1.
+ pub retries: usize,
+}
+
+impl Default for VerifMethodSmtpConfig {
+ fn default() -> Self {
+ Self {
+ from_email: "[email protected]".to_string(),
+ hello_name: "gmail.com".to_string(),
+ proxy: None,
+ smtp_port: 25,
+ smtp_timeout: None,
+ retries: 1,
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct VerifMethodSmtp {
+ pub config: VerifMethodSmtpConfig,
+ pub proxy: Option<CheckEmailInputProxy>,
+}
+
+impl VerifMethodSmtp {
+ pub fn new(config: VerifMethodSmtpConfig, proxy: Option<CheckEmailInputProxy>) -> Self {
+ Self { config, proxy }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_validate_proxies() {
+ let mut proxies = HashMap::new();
+ proxies.insert("proxy1".to_string(), CheckEmailInputProxy::default());
+ proxies.insert("proxy2".to_string(), CheckEmailInputProxy::default());
+
+ // Test invalid proxies.
+ let verif_method = VerifMethod {
+ proxies: proxies.clone(),
+ gmail: GmailVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy3".to_string()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+
+ assert!(verif_method.validate_proxies().is_err());
+
+ // Test valid proxies.
+ let verif_method = VerifMethod {
+ proxies,
+ gmail: GmailVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy1".to_string()),
+ ..Default::default()
+ }),
+ hotmailb2b: HotmailB2BVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy2".to_string()),
+ ..Default::default()
+ }),
+ hotmailb2c: HotmailB2CVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy1".to_string()),
+ ..Default::default()
+ }),
+ yahoo: YahooVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy2".to_string()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+
+ assert!(verif_method.validate_proxies().is_ok());
+ }
+
+ #[test]
+ fn test_get_proxy() {
+ let mut proxies = HashMap::new();
+ proxies.insert("proxy1".to_string(), CheckEmailInputProxy::default());
+ proxies.insert("proxy2".to_string(), CheckEmailInputProxy::default());
+
+ let verif_method = VerifMethod {
+ proxies: proxies.clone(),
+ gmail: GmailVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy1".to_string()),
+ ..Default::default()
+ }),
+ hotmailb2b: HotmailB2BVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy2".to_string()),
+ ..Default::default()
+ }),
+ hotmailb2c: HotmailB2CVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy1".to_string()),
+ ..Default::default()
+ }),
+ yahoo: YahooVerifMethod::Smtp(VerifMethodSmtpConfig {
+ proxy: Some("proxy2".to_string()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+
+ assert_eq!(
+ verif_method.get_proxy(EmailProvider::Gmail),
+ proxies.get("proxy1")
+ );
+ assert_eq!(
+ verif_method.get_proxy(EmailProvider::HotmailB2B),
+ proxies.get("proxy2")
+ );
+ assert_eq!(
+ verif_method.get_proxy(EmailProvider::HotmailB2C),
+ proxies.get("proxy1")
+ );
+ assert_eq!(
+ verif_method.get_proxy(EmailProvider::Yahoo),
+ proxies.get("proxy2")
+ );
+ assert!(verif_method
+ .get_proxy(EmailProvider::EverythingElse)
+ .is_none());
+ }
+}
diff --git a/core/src/smtp/yahoo/mod.rs b/core/src/smtp/yahoo/mod.rs
index eaf9194a..4279d015 100644
--- a/core/src/smtp/yahoo/mod.rs
+++ b/core/src/smtp/yahoo/mod.rs
@@ -60,11 +60,3 @@ impl From<SerdeError> for YahooError {
YahooError::SerdeError(error)
}
}
-
-/// Check if the MX host is from Yahoo.
-/// Examples:
-/// - mta7.am0.yahoodns.net.
-/// - mx-eu.mail.am0.yahoodns.net.
-pub fn is_yahoo(host: &str) -> bool {
- host.to_lowercase().ends_with(".yahoodns.net.")
-}
diff --git a/core/src/util/input_output.rs b/core/src/util/input_output.rs
index 0190d5ca..929349ba 100644
--- a/core/src/util/input_output.rs
+++ b/core/src/util/input_output.rs
@@ -16,6 +16,7 @@
use crate::misc::{MiscDetails, MiscError};
use crate::mx::{MxDetails, MxError};
+use crate::smtp::verif_method::VerifMethod;
use crate::smtp::{SmtpDebug, SmtpDetails, SmtpError, SmtpErrorDesc};
use crate::syntax::SyntaxDetails;
use crate::util::ser_with_display::ser_with_display;
@@ -91,7 +92,7 @@ impl AsRef<str> for EmailAddress {
/// Perform the email verification via a specified proxy. The usage of a proxy
/// is optional.
-#[derive(Debug, Default, Clone, Deserialize, Serialize)]
+#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
pub struct CheckEmailInputProxy {
/// Use the specified SOCKS5 proxy host to perform email verification.
pub host: String,
@@ -103,104 +104,6 @@ pub struct CheckEmailInputProxy {
pub password: Option<String>,
}
-/// Select how to verify Yahoo emails.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Deserialize, Serialize)]
-pub enum YahooVerifMethod {
- /// Use Yahoo's API to check if an email exists.
- Api,
- /// Use Yahoo's password recovery page to check if an email exists.
- ///
- /// This assumes you have a WebDriver compatible process running, then pass
- /// its endpoint, usually http://localhost:9515, into the environment
- /// variable RCH_WEBDRIVER_ADDR. We recommend running chromedriver (and not
- /// geckodriver) as it allows parallel requests.
- #[default]
- Headless,
- /// Use Yahoo's SMTP servers to check if an email exists.
- Smtp,
-}
-
-impl FromStr for YahooVerifMethod {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s {
- "api" => Ok(Self::Api),
- "headless" => Ok(Self::Headless),
- "smtp" => Ok(Self::Smtp),
- _ => Err(format!("Unknown yahoo verify method: {}", s)),
- }
- }
-}
-
-/// Select how to verify Gmail emails.
-#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
-pub enum GmailVerifMethod {
- /// Use Gmail's API to check if an email exists.
- Api,
- /// Use Gmail's SMTP servers to check if an email exists.
- #[default]
- Smtp,
-}
-
-impl FromStr for GmailVerifMethod {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s {
- "api" => Ok(Self::Api),
- "smtp" => Ok(Self::Smtp),
- _ => Err(format!("Unknown gmail verify method: {}", s)),
- }
- }
-}
-
-/// Select how to verify Hotmail B2B emails.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Deserialize, Serialize)]
-pub enum HotmailB2BVerifMethod {
- /// Use Hotmail's SMTP servers to check if an email exists.
- #[default]
- Smtp,
-}
-
-impl FromStr for HotmailB2BVerifMethod {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s {
- "smtp" => Ok(Self::Smtp),
- _ => Err(format!("Unknown hotmailb2b verify method: {}", s)),
- }
- }
-}
-
-/// Select how to verify Hotmail B2C emails.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Deserialize, Serialize)]
-pub enum HotmailB2CVerifMethod {
- /// Use Hotmail's password recovery page to check if an email exists.
- ///
- /// This assumes you have a WebDriver compatible process running, then pass
- /// its endpoint, usually http://localhost:9515, into the environment
- /// variable RCH_WEBDRIVER_ADDR. We recommend running chromedriver (and not
- /// geckodriver) as it allows parallel requests.
- #[default]
- Headless,
- /// Use Hotmail's SMTP servers to check if an email exists.
- Smtp,
-}
-
-impl FromStr for HotmailB2CVerifMethod {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s {
- "headless" => Ok(Self::Headless),
- "smtp" => Ok(Self::Smtp),
- _ => Err(format!("Unknown hotmailb2c verify method: {}", s)),
- }
- }
-}
-
/// Builder pattern for the input argument into the main `email_exists`
/// function.
#[derive(Builder, Debug, Clone, Deserialize, Serialize)]
@@ -208,46 +111,9 @@ impl FromStr for HotmailB2CVerifMethod {
pub struct CheckEmailInput {
/// The email to validate.
pub to_email: String,
- /// Email to use in the `MAIL FROM:` SMTP command.
- ///
- /// Defaults to "[email protected]", which is an unused addressed
- /// owned by Reacher.
- pub from_email: String,
- /// Name to use in the `EHLO:` SMTP command.
- ///
- /// Defaults to "gmail.com" (note: "localhost" is not a FQDN).
- pub hello_name: String,
- /// Perform the email verification via the specified SOCK5 proxy. The usage of a
- /// proxy is optional.
- pub proxy: Option<CheckEmailInputProxy>,
- /// SMTP port to use for email validation. Generally, ports 25, 465, 587
- /// and 2525 are used.
- ///
- /// Defaults to 25.
- pub smtp_port: u16,
- /// Add timeout for the SMTP verification step. Set to None if you don't
- /// want to use a timeout. This timeout is per SMTP connection. For
- /// instance, if you set the number of retries to 2, then the total time
- /// for the SMTP verification step can be up to 2 * `smtp_timeout`.
- ///
- /// Defaults to None.
- pub smtp_timeout: Option<Duration>,
- /// Select how to verify Yahoo emails.
- ///
- /// Defaults to Headless.
- pub yahoo_verif_method: YahooVerifMethod,
- /// Select how to verify Gmail addresses.
- ///
- /// Defaults to Smtp.
- pub gmail_verif_method: GmailVerifMethod,
- /// Select how to verify Hotmail/Outlook/Microsoft email addresses.
- ///
- /// Defaults to Headless.
- pub hotmailb2b_verif_method: HotmailB2BVerifMethod,
- /// Select how to verify Hotmail/Outlook/Microsoft email addresses.
- ///
- /// Defaults to Headless.
- pub hotmailb2c_verif_method: HotmailB2CVerifMethod,
+
+ pub verif_method: VerifMethod,
+
/// Whether to check if a gravatar image is existing for the given email.
/// Adds a bit of latency to the verification process.
///
@@ -256,14 +122,7 @@ pub struct CheckEmailInput {
/// Check if a the email address is present in HaveIBeenPwned API.
/// If the api_key is filled, HaveIBeenPwned API is checked
pub haveibeenpwned_api_key: Option<String>,
- /// Number of total SMTP connections to do. Setting to 2 might bypass
- /// greylisting on some servers, but takes more time.
- ///
- /// This setting's naming is a bit misleading, as it's not really retries,
- /// but the total number of SMTP connections to do.
- ///
- /// Defaults to 1.
- pub retries: usize,
+
/// The WebDriver address to use for headless verifications.
///
/// Defaults to http://localhost:9515.
@@ -288,18 +147,9 @@ impl Default for CheckEmailInput {
fn default() -> Self {
CheckEmailInput {
to_email: "".into(),
- from_email: "[email protected]".into(), // Unused, owned by Reacher
- hello_name: "gmail.com".into(),
- proxy: None,
- smtp_port: 25,
- smtp_timeout: None,
- yahoo_verif_method: YahooVerifMethod::default(),
- gmail_verif_method: GmailVerifMethod::default(),
- hotmailb2b_verif_method: HotmailB2BVerifMethod::default(),
- hotmailb2c_verif_method: HotmailB2CVerifMethod::default(),
+ verif_method: VerifMethod::default(),
check_gravatar: false,
haveibeenpwned_api_key: None,
- retries: 1,
webdriver_addr: "http://localhost:9515".into(),
webdriver_config: WebdriverConfig::default(),
backend_name: "backend-dev".into(),
@@ -444,17 +294,11 @@ impl Serialize for CheckEmailOutput {
}
}
-#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
+#[derive(Builder, Clone, Debug, Deserialize, Serialize, Default)]
pub struct WebdriverConfig {
pub binary: Option<String>,
}
-impl Default for WebdriverConfig {
- fn default() -> Self {
- WebdriverConfig { binary: None }
- }
-}
-
#[cfg(test)]
mod tests {
use super::{CheckEmailOutput, DebugDetails};
diff --git a/sqs/Cargo.toml b/sqs/Cargo.toml
index 40f2d094..edbee997 100644
--- a/sqs/Cargo.toml
+++ b/sqs/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "reacher_sqs"
-version = "0.10.2"
+version = "0.11.0"
edition = "2018"
license = "AGPL-3.0"
publish = false
diff --git a/sqs/src/main.rs b/sqs/src/main.rs
index 4e3e2095..439372b8 100644
--- a/sqs/src/main.rs
+++ b/sqs/src/main.rs
@@ -100,7 +100,7 @@ async fn handler(event: LambdaEvent<SQSPayload>) -> Result<CheckEmailOutput, Err
let task = &task.into_check_email_task(backend_config.clone());
- let worker_output = check_email_and_send_result(&task).await;
+ let worker_output = check_email_and_send_result(task).await;
match worker_output.as_ref() {
Ok(output) => {
info!(email = ?output.input, is_reachable = ?output.is_reachable, "Task completed");