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: Loop through all MX servers (#1070)
Amaury11e6a06a67f5
diff --git a/Cargo.lock b/Cargo.lockindex c90b40be..a3a3e662 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -318,7 +318,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"[[package]]name = "check-if-email-exists"-version = "0.8.28"+version = "0.8.29"dependencies = ["async-native-tls","async-recursion",@@ -340,7 +340,7 @@ dependencies = [[[package]]name = "check-if-email-exists-cli"-version = "0.8.28"+version = "0.8.29"dependencies = ["check-if-email-exists","clap",diff --git a/Cargo.toml b/Cargo.tomlindex 2a6022b0..c24bf988 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check-if-email-exists-cli"-version = "0.8.28"+version = "0.8.29"default-run = "check_if_email_exists"edition = "2018"description = "Check if an email address exists without sending any email."diff --git a/Dockerfile b/Dockerfileindex 89d20d5a..851c38b9 100644--- a/Dockerfile+++ b/Dockerfile@@ -8,7 +8,7 @@ FROM alpine# `ciee` stands for check-if-email-existsWORKDIR /ciee# Fetch latest version-ENV CIEE_VERSION 0.8.28+ENV CIEE_VERSION 0.8.29# Install needed librariesRUN apk update && \diff --git a/README.md b/README.mdindex 3b27d128..e64eb815 100644--- a/README.md+++ b/README.md@@ -88,7 +88,7 @@ Head to the [releases page](https://github.com/reacherhq/check-if-email-exists/r```> $ check_if_email_exists --help-check_if_email_exists 0.8.28+check_if_email_exists 0.8.29Check if an email address exists without sending any email.USAGE:diff --git a/core/Cargo.toml b/core/Cargo.tomlindex 5165677b..2f30adc9 100644--- a/core/Cargo.toml+++ b/core/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check-if-email-exists"-version = "0.8.28"+version = "0.8.29"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.rsindex 3af8e5cd..74d3f9f5 100644--- a/core/src/lib.rs+++ b/core/src/lib.rs@@ -72,7 +72,6 @@ use mx::check_mx;use smtp::{check_smtp, SmtpDetails, SmtpError};use syntax::check_syntax;use util::constants::LOG_TARGET;-pub use util::input_output::*;/// Given an email's misc and smtp details, calculate an estimate of our@@ -140,12 +139,6 @@ async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {};}};- log::debug!(- target: LOG_TARGET,- "email={} Found the following MX hosts: {:?}",- to_email,- my_mx- );// Return if we didn't find any MX records.if my_mx.lookup.is_err() {@@ -158,6 +151,19 @@ async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {};}+ log::debug!(+ target: LOG_TARGET,+ "email={} Found the following MX hosts: {:?}",+ to_email,+ my_mx+ .lookup+ .as_ref()+ .expect("If lookup is error, we already returned. qed.")+ .iter()+ .map(|host| host.exchange().to_string())+ .collect::<Vec<String>>()+ );+let my_misc = check_misc(&my_syntax);log::debug!(target: LOG_TARGET,@@ -166,28 +172,39 @@ async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {my_misc);- // We simply take the first lookup result, and connect to that SMTP server.- // FIXME Add retry mechanism to other lookup results.- let my_smtp = my_mx+ // We loop through all the MX records, and check each one of them. This is+ // because to prevent SPAM, some servers put a dummy server as 1st MX+ // record.+ // ref: https://github.com/reacherhq/check-if-email-exists/issues/1049+ let mut my_smtp: Option<Result<SmtpDetails, SmtpError>> = None;+ for host in my_mx.lookup.as_ref().expect("If lookup is error, we already returned. qed.").iter()- .next()- .map(|host| {- check_smtp(- my_syntax- .address- .as_ref()- .expect("We already checked that the email has valid format. qed."),- host.exchange(),- input.smtp_port,- my_syntax.domain.as_ref(),- &input,- )- })- .expect("Lookup cannot be empty. qed.")+ {+ let res = check_smtp(+ my_syntax+ .address+ .as_ref()+ .expect("We already checked that the email has valid format. qed."),+ host.exchange(),+ input.smtp_port,+ my_syntax.domain.as_ref(),+ &input,+ ).await;+ let is_reachable = res.is_ok();+ my_smtp = Some(res);+ if !is_reachable {+ continue; // If error, then we move on to next MX record.+ } else {+ break; // If successful, then we break.+ }+ }+ let my_smtp = my_smtp.expect(+ "As long as lookup has at least 1 element (which we checked), my_smtp will be a Some. qed.",+ );CheckEmailOutput {input: to_email.to_string(),diff --git a/core/src/smtp/mod.rs b/core/src/smtp/mod.rsindex 3f7dff61..6cfc5dba 100644--- a/core/src/smtp/mod.rs+++ b/core/src/smtp/mod.rs@@ -64,30 +64,8 @@ pub enum SmtpError {/// Error if we're using a SOCKS5 proxy.#[serde(serialize_with = "ser_with_display")]SocksError(SocksError),- /// Error when communicating with SMTP server, HELO phase.- #[serde(serialize_with = "ser_with_display")]- HeloError(AsyncSmtpError),- /// Error when communicating with SMTP server, connect phase.- #[serde(serialize_with = "ser_with_display")]- ConnectError(AsyncSmtpError),- /// Error when communicating with SMTP server, connect_with_stream phase.- #[serde(serialize_with = "ser_with_display")]- ConnectWithStreamError(AsyncSmtpError),- /// Error when communicating with SMTP server, MAIL FROM phase.- #[serde(serialize_with = "ser_with_display")]- MailFromError(AsyncSmtpError),- /// Error when communicating with SMTP server, RCPT TO phase.- #[serde(serialize_with = "ser_with_display")]- RcptToError(AsyncSmtpError),- /// Error when communicating with SMTP server, close phase.- #[serde(serialize_with = "ser_with_display")]- CloseError(AsyncSmtpError),/// Error when communicating with SMTP server.#[serde(serialize_with = "ser_with_display")]- #[deprecated(- since = "0.8.27",- note = "SMTP errors have been broken up into 6 phases, see all `Smtp*Error`s"- )]SmtpError(AsyncSmtpError),/// Time-out error.#[serde(serialize_with = "ser_with_display")]@@ -116,13 +94,13 @@ 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, $to_email: expr, $host: expr, $port: expr, $err_type: expr) => ({+ ($res: expr, $client: ident, $to_email: expr, $host: expr, $port: expr) => ({if let Err(err) = $res {log::debug!(target: LOG_TARGET, "email={} Closing {}:{}, because of error '{:?}'.", $to_email, $host, $port, err);// Try to close the connection, but ignore if there's an error.let _ = $client.close().await;- return Err($err_type(err));+ return Err(SmtpError::SmtpError(err));}}));@@ -146,21 +124,12 @@ async fn connect_to_host(let mut smtp_transport = SmtpClient::with_security((host.as_ref(), port), security).await- .map_err(SmtpError::HeloError)?+ .map_err(SmtpError::SmtpError)?// FIXME Do not clone?.hello_name(ClientId::Domain(input.hello_name.clone())).timeout(Some(Duration::new(30, 0))) // Set timeout to 30s.into_transport();- // Connect to the host. If the proxy argument is set, use it.- log::debug!(- target: LOG_TARGET,- "email={} Connecting to {}:{}",- input.to_emails[0],- host,- port- );-if let Some(proxy) = &input.proxy {let stream = match (&proxy.username, &proxy.password) {(Some(username), Some(password)) => {@@ -192,8 +161,7 @@ async fn connect_to_host(smtp_transport,input.to_emails[0],host,- port,- SmtpError::ConnectWithStreamError+ port);} else {try_smtp!(@@ -201,8 +169,7 @@ async fn connect_to_host(smtp_transport,input.to_emails[0],host,- port,- SmtpError::ConnectError+ port);}@@ -222,8 +189,7 @@ async fn connect_to_host(smtp_transport,input.to_emails[0],host,- port,- SmtpError::MailFromError+ port);Ok(smtp_transport)@@ -366,6 +332,8 @@ async fn email_deliverable(|| err_string.contains("no such recipient")// 554 delivery error: This user doesn’t have an account|| err_string.contains("have an account")+ // 5.1.1 RCP-P1 Domain facebook.com no longer available https://www.facebook.com/postmaster/response_codes?ip=3.80.111.155#RCP-P1+ || err_string.contains("no longer available"){return Ok(Deliverability {has_full_inbox: false,@@ -374,7 +342,7 @@ async fn email_deliverable(});}- Err(SmtpError::RcptToError(err))+ Err(SmtpError::SmtpError(err))}}}@@ -444,10 +412,7 @@ async fn create_smtp_future(result?};- smtp_transport- .close()- .await- .map_err(SmtpError::CloseError)?;+ smtp_transport.close().await.map_err(SmtpError::SmtpError)?;Ok((is_catch_all, deliverability))}@@ -456,12 +421,9 @@ async fn create_smtp_future(/// [`SmtpError::Error`].fn is_io_incomplete_smtp_error<T>(result: &Result<T, SmtpError>) -> bool {match result {- Err(SmtpError::HeloError(AsyncSmtpError::Io(err)))- | Err(SmtpError::ConnectError(AsyncSmtpError::Io(err)))- | Err(SmtpError::ConnectWithStreamError(AsyncSmtpError::Io(err)))- | Err(SmtpError::MailFromError(AsyncSmtpError::Io(err)))- | Err(SmtpError::RcptToError(AsyncSmtpError::Io(err)))- | Err(SmtpError::CloseError(AsyncSmtpError::Io(err))) => err.to_string().as_str() == "incomplete",+ Err(SmtpError::SmtpError(AsyncSmtpError::Io(err))) => {+ err.to_string().as_str() == "incomplete"+ }_ => false,}}@@ -511,32 +473,42 @@ async fn retry() -> Result<SmtpDetails, SmtpError> {log::debug!(target: LOG_TARGET,- "email={} Check SMTP attempt {}/{}",+ "email={} Check SMTP attempt #{} on {}:{}",input.to_emails[0],input.retries - count + 1,- input.retries,+ host,+ port);let result = check_smtp_without_retry(to_email, host, port, domain, input).await;log::debug!(target: LOG_TARGET,- "email={} Got result with attempt {}/{}, result={:?}",+ "email={} Got result for attempt #{} on {}:{}, result={:?}",input.to_emails[0],input.retries - count + 1,- input.retries,+ host,+ port,result);match result {- Ok(_) => result,- Err(_) => {+ // Only retry if the error was a temporary/transient error, or a+ // timeout error.+ Err(SmtpError::SmtpError(AsyncSmtpError::Transient(_)))+ | Err(SmtpError::SmtpError(AsyncSmtpError::Timeout(_))) => {if count <= 1 {result} else {+ log::debug!(+ target: LOG_TARGET,+ "email={} Potential greylisting detected, retrying.",+ input.to_emails[0],+ );retry(to_email, host, port, domain, input, count - 1).await}}+ _ => result,}}