Skip to content

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

feat: Revert back to `check_email` input with single email (#1150)

Amauryce1ba5346849
diff --git a/.env.example b/.env.example
new file mode 100644
index 00000000..a1d9e327
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,6 @@
+RUST_LOG=reacher=info
+
+# To enable bulk email verification, set the value below to 1, and fill out all
+other env variables below.
+RCH_ENABLE_BULK=0
+DATABASE_URL=postgres://localhost/reacherdb
diff --git a/Cargo.lock b/Cargo.lock
index 83e0fa9a..f9d05b59 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -430,7 +430,6 @@ dependencies = [
"async-smtp",
"async-std",
"async-std-resolver",
- "futures",
"log",
"mailchecker",
"rand",
@@ -443,34 +442,11 @@ dependencies = [
"trust-dns-proto",
]
-[[package]]
-name = "check-if-email-exists"
-version = "0.8.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bcefe39f6af22e8a556e3b64aefca5d58e7ed98a2e0848990f23e9b801a86a35"
-dependencies = [
- "async-native-tls",
- "async-recursion",
- "async-smtp",
- "async-std",
- "async-std-resolver",
- "futures",
- "log",
- "mailchecker",
- "rand",
- "reacher-fast-socks5",
- "regex",
- "reqwest",
- "serde",
- "serde_json",
- "trust-dns-proto",
-]
-
[[package]]
name = "check-if-email-exists-cli"
version = "0.8.32"
dependencies = [
- "check-if-email-exists 0.8.32",
+ "check-if-email-exists",
"clap",
"env_logger",
"once_cell",
@@ -1784,7 +1760,7 @@ name = "reacher_backend"
version = "0.4.0"
dependencies = [
"async-smtp",
- "check-if-email-exists 0.8.32 (registry+https://github.com/rust-lang/crates.io-index)",
+ "check-if-email-exists",
"csv",
"dotenv",
"env_logger",
diff --git a/backend/.env.example b/backend/.env.example
deleted file mode 100644
index 95db3e2c..00000000
--- a/backend/.env.example
+++ /dev/null
@@ -1 +0,0 @@
-DATABASE_URL=postgres://localhost/reacherdb
diff --git a/backend/Cargo.toml b/backend/Cargo.toml
index d34fd074..d94fa8a2 100644
--- a/backend/Cargo.toml
+++ b/backend/Cargo.toml
@@ -7,7 +7,7 @@ publish = false
[dependencies]
async-smtp = "0.5"
-check-if-email-exists = "0.8.32"
+check-if-email-exists = { path = "../core" }
csv = "1.1.6"
dotenv = "0.15.0"
env_logger = "0.9"
diff --git a/backend/src/check.rs b/backend/src/check.rs
index 879b2f80..03d9d93f 100644
--- a/backend/src/check.rs
+++ b/backend/src/check.rs
@@ -25,25 +25,13 @@ use std::time::Instant;
pub const SMTP_TIMEOUT: u64 = 10;
/// Same as `check-if-email-exists`'s check email, but adds some additional
-/// logging and error handling, and also only handles 1 email.
-///
-/// # Panics
-///
-/// If more than 1 email is passed inside input, then this function panics.
+/// logging and error handling.
pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput {
// Run `ciee_check_email` with retries if necessary. Also measure the
// verification time.
let now = Instant::now();
- assert!(
- input.to_emails.len() == 1,
- "We currently hardcode the BATCH_SIZE to 1. qed."
- );
-
- let res = ciee_check_email(input)
- .await
- .pop()
- .expect("Input only has one email, so does output. qed.");
+ let res = ciee_check_email(input).await;
// Log on Sentry the `is_reachable` field.
// We should definitely log this somewhere else than Sentry.
diff --git a/backend/src/routes/bulk/post.rs b/backend/src/routes/bulk/post.rs
index fba41544..5b523376 100644
--- a/backend/src/routes/bulk/post.rs
+++ b/backend/src/routes/bulk/post.rs
@@ -24,17 +24,8 @@ use super::{
use check_if_email_exists::CheckEmailInputProxy;
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Postgres};
-use std::cmp::min;
use warp::Filter;
-// this configures the number of emails passed to every task
-// this can be configured but will require changes in the
-// in the `crate::check::check_email` function which assumes a task can have
-// only one email. This will also require changing the
-// email_verification_task itself to handle multiple
-// outputs and commit them to the database.
-const EMAIL_TASK_BATCH_SIZE: usize = 1;
-
/// Endpoint request body.
#[derive(Clone, Debug, Deserialize, Serialize)]
struct CreateBulkRequestBody {
@@ -49,7 +40,6 @@ struct CreateBulkRequestBody {
struct CreateBulkRequestBodyIterator {
body: CreateBulkRequestBody,
index: usize,
- batch_size: usize,
}
impl IntoIterator for CreateBulkRequestBody {
@@ -60,7 +50,6 @@ impl IntoIterator for CreateBulkRequestBody {
CreateBulkRequestBodyIterator {
body: self,
index: 0,
- batch_size: EMAIL_TASK_BATCH_SIZE,
}
}
}
@@ -70,17 +59,16 @@ impl Iterator for CreateBulkRequestBodyIterator {
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.body.input.len() {
- let bounded_index = min(self.index + self.batch_size, self.body.input.len());
- let to_emails = self.body.input[self.index..bounded_index].to_vec();
+ let to_email = &self.body.input[self.index];
let item = TaskInput {
- to_emails,
+ to_email: to_email.clone(),
smtp_ports: self.body.smtp_ports.clone().unwrap_or_else(|| vec![25]),
proxy: self.body.proxy.clone(),
hello_name: self.body.hello_name.clone(),
from_email: self.body.from_email.clone(),
};
- self.index = bounded_index;
+ self.index += 1;
Some(item)
} else {
None
diff --git a/backend/src/routes/bulk/task.rs b/backend/src/routes/bulk/task.rs
index 1a607fe4..f19a81e0 100644
--- a/backend/src/routes/bulk/task.rs
+++ b/backend/src/routes/bulk/task.rs
@@ -28,8 +28,8 @@ use uuid::Uuid;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TaskInput {
// fields for CheckEmailInput
- pub to_emails: Vec<String>, // chunk of email from request. This always has at most `EMAIL_TASK_BATCH_SIZE` items.
- pub smtp_ports: Vec<u16>, // override empty smtp ports from request with default value
+ pub to_email: String, // Email from request to verify.
+ pub smtp_ports: Vec<u16>, // Ports to try for each email, in given order. Defaults to [25].
pub proxy: Option<CheckEmailInputProxy>,
pub hello_name: Option<String>,
pub from_email: Option<String>,
@@ -58,7 +58,7 @@ impl Iterator for TaskInputIterator {
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.body.smtp_ports.len() {
- let mut item = CheckEmailInput::new(self.body.to_emails.clone());
+ let mut item = CheckEmailInput::new(self.body.to_email.clone());
if let Some(name) = &self.body.hello_name {
item.set_hello_name(name.clone());
@@ -154,7 +154,7 @@ pub async fn email_verification_task(
log::debug!(
target:"reacher",
"Starting task [email={}] for [job={}] and [uuid={}]",
- check_email_input.to_emails[0],
+ check_email_input.to_email,
task_payload.id,
current_job.id(),
);
@@ -164,7 +164,7 @@ pub async fn email_verification_task(
log::debug!(
target:"reacher",
"Got task result [email={}] for [job={}] and [uuid={}] with [is_reachable={:?}]",
- check_email_input.to_emails[0],
+ check_email_input.to_email,
task_payload.id,
current_job.id(),
response.is_reachable,
diff --git a/backend/src/routes/check_email/post.rs b/backend/src/routes/check_email/post.rs
index cb4b5f2f..c077cdfb 100644
--- a/backend/src/routes/check_email/post.rs
+++ b/backend/src/routes/check_email/post.rs
@@ -35,7 +35,7 @@ pub struct EndpointRequest {
impl From<EndpointRequest> for CheckEmailInput {
fn from(req: EndpointRequest) -> Self {
// Create Request for check_if_email_exists from body
- let mut input = CheckEmailInput::new(vec![req.to_email]);
+ let mut input = CheckEmailInput::new(req.to_email);
input
.set_from_email(req.from_email.unwrap_or_else(|| {
env::var("RCH_FROM_EMAIL").unwrap_or_else(|_| "[email protected]".into())
diff --git a/cli/src/main.rs b/cli/src/main.rs
index fe184fe2..a21278ea 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -71,7 +71,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let to_email = &CONF.to_email;
- let mut input = CheckEmailInput::new(vec![to_email.clone()]);
+ let mut input = CheckEmailInput::new(to_email.clone());
input
.set_from_email(CONF.from_email.clone())
.set_hello_name(CONF.hello_name.clone())
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 920c8296..fd575647 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -19,7 +19,6 @@ async-smtp = { version = "0.5.0", features = ["socks5"] }
async-std = "1.12.0"
async-std-resolver = "0.21.2"
reacher-fast-socks5 = "0.8.1"
-futures = "0.3.23"
log = "0.4.17"
mailchecker = "5.0.0"
rand = {version = "0.8.5", features = ["small_rng"] }
diff --git a/core/src/lib.rs b/core/src/lib.rs
index db5dfad2..4104b69f 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -38,7 +38,7 @@
//!
//! async fn check() {
//! // Let's say we want to test the deliverability of [email protected].
-//! let mut input = CheckEmailInput::new(vec!["[email protected]".into()]);
+//! let mut input = CheckEmailInput::new("[email protected]".into());
//!
//! // Optionally, we can also tweak the configuration parameters used in the
//! // verification.
@@ -68,7 +68,6 @@ pub mod smtp;
pub mod syntax;
mod util;
-use futures::future;
use misc::{check_misc, MiscDetails};
use mx::check_mx;
use smtp::{check_smtp, SmtpDetails, SmtpError};
@@ -94,15 +93,18 @@ fn calculate_reachable(misc: &MiscDetails, smtp: &Result<SmtpDetails, SmtpError>
}
}
-/// Check a single emails. This assumes this `input.check_email` contains
-/// exactly one element. If it contains more, elements other than the first
-/// one will be ignored.
+/// The main function of this library: verify a single email. Performs, in the
+/// following order, 4 types of verifications:
+/// - syntax check: verify the email is well-formed,
+/// - MX checks: verify the domain is configured to receive email,
+/// - SMTP checks: connect to the SMTP server and verify the email is
+/// deliverable,
+/// - misc checks: metadata about the email provider.
///
-/// # Panics
-///
-/// This function panics if `input.check_email` is empty.
-async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {
- let to_email = &input.to_emails[0];
+/// Returns a `CheckEmailOutput` output, whose `is_reachable` field is one of
+/// `Safe`, `Invalid`, `Risky` or `Unknown`.
+pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput {
+ let to_email = &input.to_email;
log::debug!(
target: LOG_TARGET,
@@ -193,7 +195,7 @@ async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {
host.exchange(),
input.smtp_port,
my_syntax.domain.as_ref(),
- &input,
+ input,
)
.await;
let is_reachable = res.is_ok();
@@ -217,43 +219,3 @@ async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {
syntax: my_syntax,
}
}
-
-/// The main function of this library: takes as input a list of email addresses
-/// to check. Then performs syntax, mx, smtp and misc checks, and outputs a
-/// list of results.
-///
-/// Please note that checking multiple emails at once (by putting multiple
-/// emails in the `inputs.to_emails` Vec) is still a **beta** feature, and not
-/// fully optimized. For more info, see #65
-/// <https://github.com/reacherhq/check-if-email-exists/issues/65>.
-pub async fn check_email(inputs: &CheckEmailInput) -> Vec<CheckEmailOutput> {
- if inputs.to_emails.len() > 1 {
- log::warn!(
- target: LOG_TARGET,
- "Verifying multiple emails with this library is still a beta feature, please don't overuse it. See reacherhq/check-if-email-exists #65."
- );
- }
-
- // FIXME Obviously, the below `join_all` is not optimal. Some optimizations
- // include:
- // - if multiple email addresses share the same domain, we should only do
- // `check_mx` call for all these email addresses.
- // - if multiple email addresses share the same domain, we should call
- // `check_smtp` with grouped email addresses, to share a SMTP connection.
- // ref: https://github.com/reacherhq/check-if-email-exists/issues/65.
- let inputs = inputs.to_emails.iter().map(|email| {
- // Create n `CheckEmailInput`s, each with one email address.
- CheckEmailInput {
- to_emails: vec![email.clone()],
- 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_security: inputs.smtp_security,
- smtp_timeout: inputs.smtp_timeout,
- yahoo_use_api: inputs.yahoo_use_api,
- }
- });
- future::join_all(inputs.map(check_single_email)).await
-}
diff --git a/core/src/smtp/mod.rs b/core/src/smtp/mod.rs
index ce5fc0b6..8d068201 100644
--- a/core/src/smtp/mod.rs
+++ b/core/src/smtp/mod.rs
@@ -113,7 +113,7 @@ async fn connect_to_host(
try_smtp!(
smtp_transport.connect().await,
smtp_transport,
- input.to_emails[0],
+ input.to_email,
host,
port
);
@@ -131,7 +131,7 @@ async fn connect_to_host(
.command(MailCommand::new(Some(from_email), vec![],))
.await,
smtp_transport,
- input.to_emails[0],
+ input.to_email,
host,
port
);
@@ -156,8 +156,8 @@ async fn email_deliverable(
smtp_transport: &mut SmtpTransport,
to_email: &EmailAddress,
) -> Result<Deliverability, SmtpError> {
- // "RCPT TO: [email protected]"
- // FIXME Do not clone?
+ // "RCPT TO: <target email>"
+ // FIXME Do not clone `to_email`?
match smtp_transport
.command(RcptCommand::new(to_email.clone(), vec![]))
.await
@@ -349,7 +349,7 @@ async fn retry(
log::debug!(
target: LOG_TARGET,
"email={} Check SMTP attempt #{} on {}:{}",
- input.to_emails[0],
+ input.to_email,
input.retries - count + 1,
host,
port
@@ -360,7 +360,7 @@ async fn retry(
log::debug!(
target: LOG_TARGET,
"email={} Got result for attempt #{} on {}:{}, result={:?}",
- input.to_emails[0],
+ input.to_email,
input.retries - count + 1,
host,
port,
@@ -378,7 +378,7 @@ async fn retry(
log::debug!(
target: LOG_TARGET,
"email={} Potential greylisting detected, retrying.",
- input.to_emails[0],
+ input.to_email,
);
retry(to_email, host, port, domain, input, count - 1).await
}
diff --git a/core/src/smtp/yahoo.rs b/core/src/smtp/yahoo.rs
index 59b9355c..53dee561 100644
--- a/core/src/smtp/yahoo.rs
+++ b/core/src/smtp/yahoo.rs
@@ -111,7 +111,7 @@ fn create_client(input: &CheckEmailInput) -> Result<reqwest::Client, ReqwestErro
log::debug!(
target: LOG_TARGET,
"email={} Using proxy socks://{}:{} for Yahoo API",
- input.to_emails[0],
+ input.to_email,
proxy.host,
proxy.port
);
diff --git a/core/src/util/input_output.rs b/core/src/util/input_output.rs
index 00bcf7df..ddbc178e 100644
--- a/core/src/util/input_output.rs
+++ b/core/src/util/input_output.rs
@@ -66,7 +66,7 @@ impl SmtpSecurity {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CheckEmailInput {
/// The email to validate.
- pub to_emails: Vec<String>,
+ pub to_email: String,
/// Email to use in the `MAIL FROM:` SMTP command.
///
/// Defaults to "[email protected]".
@@ -103,7 +103,7 @@ pub struct CheckEmailInput {
impl Default for CheckEmailInput {
fn default() -> Self {
CheckEmailInput {
- to_emails: vec![],
+ to_email: "".into(),
from_email: "[email protected]".into(),
hello_name: "localhost".into(),
proxy: None,
@@ -118,9 +118,9 @@ impl Default for CheckEmailInput {
impl CheckEmailInput {
/// Create a new CheckEmailInput.
- pub fn new(to_emails: Vec<String>) -> CheckEmailInput {
+ pub fn new(to_email: String) -> CheckEmailInput {
CheckEmailInput {
- to_emails,
+ to_email,
..Default::default()
}
}