Check if an email address exists without sending any email, written in Rust. Comes with a ⚙️ HTTP backend.
Rust emailemail-validationemail-validation-apiemail-verificationemail-verification-apiemail-verifierhacktoberfest
feat: Add SMTP retries to avoid greylisting (#1041)
Amauryb451a1e93a6c
diff --git a/Cargo.lock b/Cargo.lockindex 876f59d3..565f073f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -137,6 +137,17 @@ dependencies = ["winapi",]+[[package]]+name = "async-recursion"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2cda8f4bcc10624c4e85bc66b3f452cca98cfa5ca002dc83a16aad2367641bea"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "async-smtp"version = "0.4.0"@@ -310,6 +321,7 @@ name = "check-if-email-exists"version = "0.8.25"dependencies = ["async-native-tls",+ "async-recursion","async-smtp","async-std","async-std-resolver",diff --git a/core/Cargo.toml b/core/Cargo.tomlindex 4a99d806..5a9354fc 100644--- a/core/Cargo.toml+++ b/core/Cargo.toml@@ -18,6 +18,7 @@ travis-ci = { repository = "reacherhq/check-if-email-exists", service = "github"[dependencies]async-native-tls = "0.3.3"+async-recursion = "1.0.0"async-smtp = { version = "0.4.0", features = ["socks5"] }async-std = "1.10.0"async-std-resolver = "0.20.3"diff --git a/core/src/lib.rs b/core/src/lib.rsindex cc2644b4..5c911dc8 100644--- a/core/src/lib.rs+++ b/core/src/lib.rs@@ -103,7 +103,12 @@ fn calculate_reachable(misc: &MiscDetails, smtp: &Result<SmtpDetails, SmtpError>async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {let to_email = &input.to_emails[0];- log::debug!(target: LOG_TARGET, "Checking email \"{}\"", to_email);+ log::debug!(+ target: LOG_TARGET,+ "email={} Checking email \"{}\"",+ to_email,+ to_email+ );let my_syntax = check_syntax(to_email.as_ref());if !my_syntax.is_valid_syntax {return CheckEmailOutput {@@ -116,7 +121,8 @@ async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {log::debug!(target: LOG_TARGET,- "Found the following syntax validation: {:?}",+ "email={} Found the following syntax validation: {:?}",+ to_email,my_syntax);@@ -136,7 +142,8 @@ async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {};log::debug!(target: LOG_TARGET,- "Found the following MX hosts {:?}",+ "email={} Found the following MX hosts {:?}",+ to_email,my_mx);@@ -154,7 +161,8 @@ async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {let my_misc = check_misc(&my_syntax);log::debug!(target: LOG_TARGET,- "Found the following misc details: {:?}",+ "email={} Found the following misc details: {:?}",+ to_email,my_misc);@@ -214,6 +222,7 @@ pub async fn check_email(inputs: &CheckEmailInput) -> Vec<CheckEmailOutput> {from_email: inputs.from_email.clone(),hello_name: inputs.hello_name.clone(),proxy: inputs.proxy.clone(),+ retries: inputs.retries,smtp_port: inputs.smtp_port,smtp_timeout: inputs.smtp_timeout,yahoo_use_api: inputs.yahoo_use_api,diff --git a/core/src/smtp/mod.rs b/core/src/smtp/mod.rsindex 56d0c847..5a5b3dd6 100644--- a/core/src/smtp/mod.rs+++ b/core/src/smtp/mod.rs@@ -19,6 +19,7 @@ mod yahoo;use super::util::{constants::LOG_TARGET, input_output::CheckEmailInput};use crate::util::ser_with_display::ser_with_display;use async_native_tls::TlsConnector;+use async_recursion::async_recursion;use async_smtp::{smtp::{client::net::NetworkStream, commands::*, error::Error as AsyncSmtpError,@@ -99,9 +100,9 @@ impl From<YahooError> for SmtpError {/// Try to send an smtp command, close and return Err if fails.macro_rules! try_smtp (- ($res: expr, $client: ident, $host: expr, $port: expr) => ({+ ($res: expr, $client: ident, $to_email: expr, $host: expr, $port: expr) => ({if let Err(err) = $res {- log::debug!(target: LOG_TARGET, "Closing {}:{}, because of error '{}'.", $host, $port, err);+ log::debug!(target: LOG_TARGET, "email={} Closing {}:{}, because of error '{:?}'.", $to_email, $host, $port, err);$client.close().await?;return Err(err.into());@@ -131,7 +132,13 @@ async fn connect_to_host(.into_transport();// Connect to the host. If the proxy argument is set, use it.- log::debug!(target: LOG_TARGET, "Connecting to {}:{}", host, port);+ log::debug!(+ target: LOG_TARGET,+ "email={} Connecting to {}:{}",+ input.to_emails[0],+ host,+ port+ );if let Some(proxy) = &input.proxy {let stream = Socks5Stream::connect((proxy.host.as_ref(), proxy.port),@@ -146,11 +153,18 @@ async fn connect_to_host(.connect_with_stream(NetworkStream::Socks5Stream(stream)).await,smtp_client,+ input.to_emails[0],host,port);} else {- try_smtp!(smtp_client.connect().await, smtp_client, host, port);+ try_smtp!(+ smtp_client.connect().await,+ smtp_client,+ input.to_emails[0],+ host,+ port+ );}// "MAIL FROM: [email protected]"@@ -167,6 +181,7 @@ async fn connect_to_host(.command(MailCommand::new(Some(from_email.clone()), vec![],)).await,smtp_client,+ input.to_emails[0],host,port);@@ -399,8 +414,9 @@ fn is_io_incomplete_smtp_error<T>(result: &Result<T, SmtpError>) -> bool {}}-/// Get all email details we can from one single `EmailAddress`.-pub async fn check_smtp(+/// Get all email details we can from one single `EmailAddress`, without+/// retries.+async fn check_smtp_without_retry(to_email: &EmailAddress,host: &Name,port: u16,@@ -430,6 +446,60 @@ pub async fn check_smtp(})}+/// Get all email details we can from one single `EmailAddress`.+/// Retry the SMTP connection, in particular to avoid greylisting.+#[async_recursion]+async fn retry(+ to_email: &EmailAddress,+ host: &Name,+ port: u16,+ domain: &str,+ input: &CheckEmailInput,+ count: usize,+) -> Result<SmtpDetails, SmtpError> {+ log::debug!(+ target: LOG_TARGET,+ "email={} Check SMTP attempt {}/{}",+ input.to_emails[0],+ input.retries - count + 1,+ input.retries,+ );++ let result = check_smtp_without_retry(to_email, host, port, domain, input).await;++ log::debug!(+ target: LOG_TARGET,+ "email={} Got result with attempt {}/{}, result={:?}",+ input.to_emails[0],+ input.retries - count + 1,+ input.retries,+ result+ );++ match result {+ Ok(_) => result,+ Err(_) => {+ if count <= 1 {+ result+ } else {+ retry(to_email, host, port, domain, input, count - 1).await+ }+ }+ }+}++/// Get all email details we can from one single `EmailAddress`, without+/// retries.+pub async fn check_smtp(+ to_email: &EmailAddress,+ host: &Name,+ port: u16,+ domain: &str,+ input: &CheckEmailInput,+) -> Result<SmtpDetails, SmtpError> {+ retry(to_email, host, port, domain, input, input.retries).await+}+#[cfg(test)]mod tests {use super::{check_smtp, CheckEmailInput, SmtpError};diff --git a/core/src/smtp/yahoo.rs b/core/src/smtp/yahoo.rsindex 83350601..15da9140 100644--- a/core/src/smtp/yahoo.rs+++ b/core/src/smtp/yahoo.rs@@ -110,7 +110,8 @@ fn create_client(input: &CheckEmailInput) -> Result<reqwest::Client, ReqwestErroif let Some(proxy) = &input.proxy {log::debug!(target: LOG_TARGET,- "Using proxy socks://{}:{} for Yahoo API",+ "email={} Using proxy socks://{}:{} for Yahoo API",+ input.to_emails[0],proxy.host,proxy.port);@@ -141,10 +142,21 @@ pub async fn check_yahoo(return Err(YahooError::NoCookie);}};- log::debug!(target: LOG_TARGET, "Yahoo 1st response: {:?}", response);- log::debug!(target: LOG_TARGET, "Yahoo cookies: {:?}", cookies);let to_email = to_email.to_string();+ log::debug!(+ target: LOG_TARGET,+ "email={} Yahoo 1st response: {:?}",+ to_email,+ response+ );+ log::debug!(+ target: LOG_TARGET,+ "email={} Yahoo cookies: {:?}",+ to_email,+ cookies+ );+let username = to_email.split('@').next()@@ -189,7 +201,12 @@ pub async fn check_yahoo(.json::<FormResponse>().await?;- log::debug!(target: LOG_TARGET, "Yahoo 2nd response: {:?}", response);+ log::debug!(+ target: LOG_TARGET,+ "email={} Yahoo 2nd response: {:?}",+ to_email,+ response+ );let username_exists = response.errorsdiff --git a/core/src/util/input_output.rs b/core/src/util/input_output.rsindex 190aecb0..61b19382 100644--- a/core/src/util/input_output.rs+++ b/core/src/util/input_output.rs@@ -60,6 +60,9 @@ pub struct CheckEmailInput {////// Defaults to true.pub yahoo_use_api: bool,+ /// Number of retries of SMTP connections to do. Defaults to 2 to avoid+ /// greylisting.+ pub retries: usize,}impl Default for CheckEmailInput {@@ -72,6 +75,7 @@ impl Default for CheckEmailInput {smtp_port: 25,smtp_timeout: None,yahoo_use_api: true,+ retries: 2,}}}@@ -131,6 +135,12 @@ impl CheckEmailInput {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 {