Skip to content

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

refactor!: Rename main function to `check_email` (#319)

Amaury Martinybd12b7dbbd6c
diff --git a/.editorconfig b/.editorconfig
index 116a73c7..a14fd4f0 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -8,7 +8,7 @@ tab_width=4
end_of_line=lf
charset=utf-8
trim_trailing_whitespace=true
-max_line_length=120
+max_line_length=80
insert_final_newline=true
[*.{yml,sh}]
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index f88d5f4d..86d96c99 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -1,6 +1,6 @@
# Based on https://github.com/actions-rs/meta/blob/master/recipes/quickstart.md
-name: pr
+name: CI
on: [pull_request]
@@ -24,7 +24,11 @@ jobs:
command: check
test:
- runs-on: ubuntu-latest
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [ubuntu-latest, windows-latest, macOS-latest]
+
steps:
- name: Checkout sources
uses: actions/checkout@v1
@@ -42,21 +46,6 @@ jobs:
command: test
args: --all
- e2e:
- runs-on: ${{ matrix.os }}
- strategy:
- matrix:
- os: [ubuntu-latest, windows-latest, macOS-latest]
-
- steps:
- - uses: hecrj/setup-rust-action@v1
-
- - name: Checkout sources
- uses: actions/checkout@v1
-
- - name: Run tests
- run: cargo run -- [email protected] | grep "is_deliverable" # If `is_deliverable` shows up, it means that the SMTP checks happened
-
lints:
runs-on: ubuntu-latest
steps:
diff --git a/.gitignore b/.gitignore
index ecbd5bb6..695a3d7a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,6 @@
/target
**/*.rs.bk
.DS_Store
+
+# sensitive data
+/test_suite/src/sensitive_fixtures/*.json
diff --git a/Cargo.lock b/Cargo.lock
index 85083306..a7c991ae 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -213,7 +213,7 @@ checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "check-if-email-exists"
-version = "0.7.1"
+version = "0.8.0"
dependencies = [
"amaurymartiny-async-smtp",
"fast-socks5",
@@ -228,7 +228,7 @@ dependencies = [
[[package]]
name = "check-if-email-exists-cli"
-version = "0.7.1"
+version = "0.8.0"
dependencies = [
"check-if-email-exists",
"clap",
@@ -241,7 +241,7 @@ dependencies = [
[[package]]
name = "check-if-email-exists-test-suite"
-version = "0.7.1"
+version = "0.8.0"
dependencies = [
"check-if-email-exists",
"serde",
diff --git a/Cargo.toml b/Cargo.toml
index 707e3a17..139e3f15 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "check-if-email-exists-cli"
-version = "0.7.1"
+version = "0.8.0"
default-run = "check_if_email_exists"
edition = "2018"
license = "GPL-3.0"
diff --git a/Dockerfile b/Dockerfile
index 198c6ce1..b5c694c6 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -3,7 +3,7 @@ FROM alpine
# `ciee` stands for check-if-email-exists
WORKDIR /ciee
# Fetch latest version
-ENV CIEE_VERSION 0.7.1
+ENV CIEE_VERSION 0.8.0
# Install needed libraries
RUN apk update && \
diff --git a/README.md b/README.md
index 1ac05b0f..9d4892ca 100644
--- a/README.md
+++ b/README.md
@@ -199,7 +199,7 @@ The output will be a JSON with the below format, the fields should be self-expla
}
```
-You can also take a look at the [OpenAPIv3 specification](https://stoplight.io/p/docs/gh/reacherhq/openapi/openapi.json/components/schemas/EmailResult?srn=gh/reacherhq/openapi/openapi.json/components/schemas/EmailResult) of this JSON object.
+You can also take a look at the [OpenAPIv3 specification](https://stoplight.io/p/docs/gh/reacherhq/openapi/openapi.json/components/schemas/EmailResult?srn=gh/reacherhq/backend/openapi.json/components/schemas/EmailResult) of this JSON object.
## ❓ FAQ
diff --git a/ci/script.sh b/ci/script.sh
index 6318df94..85c4148f 100755
--- a/ci/script.sh
+++ b/ci/script.sh
@@ -11,16 +11,15 @@ main() {
return
fi
- cross test --all --target $TARGET
- cross test --all --target $TARGET --release
-
- # Run the binary with a $TEST_EMAIL, to test that the tool actually works.
- # aka some quick e2e test on the binary itself
- # TODO This only works on osx now, see #11
+ # FIXME This only works on osx now
+ # See https://github.com/amaurymartiny/check-if-email-exists/issues/11
if [ $TRAVIS_OS_NAME = osx ]; then
- cross run --target $TARGET $TEST_EMAIL | grep "\"is_deliverable\": true"
- cross run --target $TARGET --release $TEST_EMAIL | grep "\"is_deliverable\": true"
+ cross test --all --target $TARGET
+ cross test --all --target $TARGET --release
fi
+
+ cross run --target $TARGET
+ cross run --target $TARGET --release
}
# we don't run the "test phase" when doing deploys
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 6edb5fe4..9ce9fc63 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "check-if-email-exists"
-version = "0.7.1"
+version = "0.8.0"
authors = ["Amaury Martiny <[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 9535fd33..66a9a125 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -34,11 +34,11 @@
//! - Catch-all address. Is this email address a catch-all address?
//!
//! ```rust
-//! use check_if_email_exists::{email_exists, EmailInput};
+//! use check_if_email_exists::{check_email, CheckEmailInput};
//!
//! async fn check() {
//! // Let's say we want to test the deliverability of [email protected].
-//! let mut input = EmailInput::new("[email protected]".into());
+//! let mut input = CheckEmailInput::new(vec!["[email protected]".into()]);
//!
//! // Optionally, we can also tweak the configuration parameters used in the
//! // verification.
@@ -47,10 +47,10 @@
//! .hello_name("example.org".into()); // Used in the `EHLO` command
//!
//! // Verify this input, using async/await syntax.
-//! let result = email_exists(&input).await;
+//! let result = check_email(&input).await;
//!
-//! // `result` is a `SingleEmail` struct containing all information about the
-//! // email.
+//! // `result` is a `Vec<CheckEmailOutput>`, where the CheckEmailOutput
+//! // struct contains all information about one email.
//! println!("{:?}", result);
//! }
//! ```
@@ -58,147 +58,157 @@
#[macro_use]
extern crate log;
-pub mod misc;
-pub mod mx;
-pub mod smtp;
-pub mod syntax;
+mod misc;
+mod mx;
+mod smtp;
+mod syntax;
mod util;
use async_smtp::{smtp::SMTP_PORT, EmailAddress};
-use futures::future::select_ok;
-use misc::{misc_details, MiscDetails, MiscError};
-use mx::{get_mx_lookup, MxDetails, MxError};
-use serde::{ser::SerializeMap, Serialize, Serializer};
-use smtp::{SmtpDetails, SmtpError};
+use futures::future;
+use misc::check_misc;
+use mx::check_mx;
+use smtp::check_smtp;
use std::str::FromStr;
-use syntax::{address_syntax, SyntaxDetails, SyntaxError};
-
-pub use util::email_input::*;
-
-/// All details about email address, MX records and SMTP responses
-#[derive(Debug)]
-pub struct SingleEmail {
- /// Input by the user
- pub input: String,
- /// Misc details about the email address
- pub misc: Result<MiscDetails, MiscError>,
- /// Details about the MX host
- pub mx: Result<MxDetails, MxError>,
- /// Details about the SMTP responses of the email
- pub smtp: Result<SmtpDetails, SmtpError>, // TODO Better Err type
- /// Details about the email address
- pub syntax: Result<SyntaxDetails, SyntaxError>,
-}
-
-// Implement a custom serialize
-impl Serialize for SingleEmail {
- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where
- S: Serializer,
- {
- // This is just used internally to get the nested error field
- #[derive(Serialize)]
- struct MyError<E> {
- error: E,
- }
-
- let mut map = serializer.serialize_map(Some(1))?;
- map.serialize_entry("input", &self.input)?;
- match &self.misc {
- Ok(t) => map.serialize_entry("misc", &t)?,
- Err(error) => map.serialize_entry("misc", &MyError { error })?,
- }
- match &self.mx {
- Ok(t) => map.serialize_entry("mx", &t)?,
- Err(error) => map.serialize_entry("mx", &MyError { error })?,
- }
- match &self.smtp {
- Ok(t) => map.serialize_entry("smtp", &t)?,
- Err(error) => map.serialize_entry("smtp", &MyError { error })?,
- }
- match &self.syntax {
- Ok(t) => map.serialize_entry("syntax", &t)?,
- Err(error) => map.serialize_entry("syntax", &MyError { error })?,
- }
- map.end()
- }
-}
-
-/// The main function: checks email format, checks MX records, and checks SMTP
-/// responses to the email inbox.
-pub async fn email_exists(email_input: &EmailInput) -> SingleEmail {
- let from_email = EmailAddress::from_str(email_input.from_email.as_ref()).unwrap_or_else(|_| {
+use syntax::check_syntax;
+use util::constants::LOG_TARGET;
+
+pub use util::input_output::*;
+
+/// 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.
+///
+/// # Panics
+///
+/// This function panics if `input.check_email` is empty.
+async fn check_single_email(input: CheckEmailInput) -> CheckEmailOutput {
+ let from_email = EmailAddress::from_str(input.from_email.as_ref()).unwrap_or_else(|_| {
warn!(
"Inputted from_email \"{}\" is not a valid email, using \"[email protected]\" instead",
- email_input.from_email
+ input.from_email
);
EmailAddress::from_str("[email protected]").expect("This is a valid email. qed.")
});
- debug!("Checking email \"{}\"", email_input.to_email);
- let my_syntax = match address_syntax(email_input.to_email.as_ref()) {
- Ok(s) => s,
- e => {
- return SingleEmail {
- input: email_input.to_email.to_string(),
- misc: Err(MiscError::Skipped),
- mx: Err(MxError::Skipped),
- smtp: Err(SmtpError::Skipped),
- syntax: e,
- }
- }
- };
- debug!("Found the following syntax validation: {:?}", my_syntax);
+ let to_email = &input.to_emails[0];
+
+ debug!(target: LOG_TARGET, "Checking email \"{}\"", to_email);
+ let my_syntax = check_syntax(to_email.as_ref());
+ if !my_syntax.is_valid_syntax {
+ return CheckEmailOutput {
+ input: to_email.to_string(),
+ syntax: my_syntax,
+ ..Default::default()
+ };
+ }
+
+ debug!(
+ target: LOG_TARGET,
+ "Found the following syntax validation: {:?}", my_syntax
+ );
- let my_mx = match get_mx_lookup(&my_syntax).await {
+ let my_mx = match check_mx(&my_syntax).await {
Ok(m) => m,
e => {
- return SingleEmail {
- input: email_input.to_email.to_string(),
- misc: Err(MiscError::Skipped),
+ return CheckEmailOutput {
+ input: to_email.to_string(),
mx: e,
- smtp: Err(SmtpError::Skipped),
- syntax: Ok(my_syntax),
+ syntax: my_syntax,
+ ..Default::default()
}
}
};
- debug!("Found the following MX hosts {:?}", my_mx);
-
- let my_misc = misc_details(&my_syntax);
- debug!("Found the following misc details: {:?}", my_misc);
+ debug!(
+ target: LOG_TARGET,
+ "Found the following MX hosts {:?}", my_mx
+ );
+
+ // Return if we didn't find any MX records.
+ if my_mx.lookup.is_err() {
+ return CheckEmailOutput {
+ input: to_email.to_string(),
+ mx: Ok(my_mx),
+ syntax: my_syntax,
+ ..Default::default()
+ };
+ }
- // Create one future per lookup result
+ let my_misc = check_misc(
+ &my_syntax
+ .address
+ .as_ref()
+ .expect("We already checked that the email has valid format. qed.")
+ .as_ref(),
+ );
+ debug!(
+ target: LOG_TARGET,
+ "Found the following misc details: {:?}", my_misc
+ );
+
+ // Create one future per lookup result.
let futures = my_mx
.lookup
- .iter()
- .map(|host| {
- let fut = smtp::smtp_details(
- &from_email,
- &my_syntax.address,
- host.exchange(),
- // We could add ports 465 and 587 too
- SMTP_PORT,
- my_syntax.domain.as_str(),
- email_input.hello_name.as_ref(),
- &email_input.proxy,
- );
-
- // https://rust-lang.github.io/async-book/04_pinning/01_chapter.html
- Box::pin(fut)
+ .as_ref()
+ .map(|lookup| {
+ lookup
+ .iter()
+ .map(|host| {
+ let fut = check_smtp(
+ my_syntax
+ .address
+ .as_ref()
+ .expect("We already checked that the email has valid format. qed."),
+ &from_email,
+ host.exchange(),
+ // FIXME We could add ports 465 and 587 too.
+ SMTP_PORT,
+ my_syntax.domain.as_ref(),
+ input.hello_name.as_ref(),
+ &input.proxy,
+ );
+
+ // https://rust-lang.github.io/async-book/04_pinning/01_chapter.html
+ Box::pin(fut)
+ })
+ .collect::<Vec<_>>()
})
- .collect::<Vec<_>>();
+ .expect("If lookup is empty, we already returned. qed.");
- // Race, return the first future that resolves
- let my_smtp = match select_ok(futures).await {
+ // Race, return the first future that resolves.
+ let my_smtp = match future::select_ok(futures).await {
Ok((details, _)) => Ok(details),
Err(err) => Err(err),
};
- SingleEmail {
- input: email_input.to_email.to_string(),
+ CheckEmailOutput {
+ input: to_email.to_string(),
misc: Ok(my_misc),
mx: Ok(my_mx),
smtp: my_smtp,
- syntax: Ok(my_syntax),
+ 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.
+pub async fn check_email(inputs: &CheckEmailInput) -> Vec<CheckEmailOutput> {
+ // 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.
+ // Also see https://github.com/amaurymartiny/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(),
+ }
+ });
+ future::join_all(inputs.map(check_single_email)).await
+}
diff --git a/core/src/misc.rs b/core/src/misc.rs
index 5e779037..27e186e6 100644
--- a/core/src/misc.rs
+++ b/core/src/misc.rs
@@ -14,30 +14,36 @@
// You should have received a copy of the GNU General Public License
// along with check-if-email-exists. If not, see <http://www.gnu.org/licenses/>.
-use crate::syntax::SyntaxDetails;
use serde::Serialize;
-/// Details that we gathered from connecting to this email via SMTP
+/// Details that we gathered from connecting to this email via SMTP.
#[derive(Debug, Serialize)]
pub struct MiscDetails {
/// Is this a DEA (disposable email account)?
pub is_disposable: bool,
}
-/// Error occured connecting to this email server via SMTP
+impl Default for MiscDetails {
+ fn default() -> Self {
+ MiscDetails {
+ is_disposable: false,
+ }
+ }
+}
+
+/// Error occured connecting to this email server via SMTP. Right now this
+/// enum has no variant, as `check_misc` cannot fail. But putting a placeholder
+/// right now to avoid future breaking changes.
#[derive(Debug, Serialize)]
#[serde(tag = "type", content = "message")]
-pub enum MiscError {
- /// Skipped checking SMTP details
- Skipped,
-}
+pub enum MiscError {}
-/// Fetch misc details about the email address, such as whether it's disposable
-pub fn misc_details(syntax: &SyntaxDetails) -> MiscDetails {
+/// Fetch misc details about the email address, such as whether it's disposable.
+pub fn check_misc(address: &str) -> MiscDetails {
MiscDetails {
// mailchecker::is_valid checks also if the syntax is valid. But if
// we're here, it means we're sure the syntax is valid, so is_valid
- // actually will only check the disposable email Misc.
- is_disposable: !mailchecker::is_valid(syntax.address.to_string().as_ref()),
+ // actually will only check if it's disposable.
+ is_disposable: !mailchecker::is_valid(address),
}
}
diff --git a/core/src/mx.rs b/core/src/mx.rs
index 2ea9aa26..b4690abf 100644
--- a/core/src/mx.rs
+++ b/core/src/mx.rs
@@ -20,16 +20,24 @@ use serde::{ser::SerializeMap, Serialize, Serializer};
use std::io::Error;
use trust_dns_resolver::{config::*, error::ResolveError, lookup::MxLookup, TokioAsyncResolver};
-/// Details about the MX lookup
+/// Details about the MX lookup.
#[derive(Debug)]
pub struct MxDetails {
- /// MX lookup of this DNS
- pub lookup: MxLookup,
+ /// MX lookup of this DNS.
+ pub lookup: Result<MxLookup, ResolveError>,
+}
+
+impl Default for MxDetails {
+ fn default() -> Self {
+ MxDetails {
+ lookup: Err(ResolveError::from("Skipped")),
+ }
+ }
}
impl From<MxLookup> for MxDetails {
fn from(lookup: MxLookup) -> Self {
- MxDetails { lookup }
+ MxDetails { lookup: Ok(lookup) }
}
}
@@ -38,29 +46,32 @@ impl Serialize for MxDetails {
where
S: Serializer,
{
- let mut map = serializer.serialize_map(Some(1))?;
- map.serialize_entry(
- "records",
- &self
- .lookup
- .iter()
- .map(|host| host.exchange().to_string())
- .collect::<Vec<_>>(),
- )?;
+ let records = self
+ .lookup
+ .as_ref()
+ .map(|lookup| {
+ lookup
+ .iter()
+ .map(|host| host.exchange().to_string())
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_else(|_| vec![]); // In case of a resolve error, we don't serialize the error.
+
+ let mut map = serializer.serialize_map(Some(2))?;
+ map.serialize_entry("accepts_mail", &!records.is_empty())?;
+ map.serialize_entry("records", &records)?;
map.end()
}
}
-/// Errors that can happen on MX lookups
+/// Errors that can happen on MX lookups.
#[derive(Debug, Serialize)]
#[serde(tag = "type", content = "message")]
pub enum MxError {
- /// Skipped checking MX records
- Skipped,
- /// Error with IO
+ /// Error with IO.
#[serde(serialize_with = "ser_with_display")]
IoError(Error),
- /// Error while resolving MX lookups
+ /// Error while resolving MX lookups.
#[serde(serialize_with = "ser_with_display")]
ResolveError(ResolveError),
}
@@ -71,8 +82,8 @@ impl From<ResolveError> for MxError {
}
}
-/// Make a MX lookup
-pub async fn get_mx_lookup(syntax: &SyntaxDetails) -> Result<MxDetails, MxError> {
+/// Make a MX lookup.
+pub async fn check_mx(syntax: &SyntaxDetails) -> Result<MxDetails, MxError> {
// Construct a new Resolver with default configuration options
let resolver =
TokioAsyncResolver::tokio(ResolverConfig::default(), ResolverOpts::default()).await?;
@@ -82,6 +93,6 @@ pub async fn get_mx_lookup(syntax: &SyntaxDetails) -> Result<MxDetails, MxError>
// in `ResolverOpts` will take effect. FQDN's are generally cheaper queries.
match resolver.mx_lookup(syntax.domain.as_ref()).await {
Ok(lookup) => Ok(MxDetails::from(lookup)),
- Err(err) => Err(MxError::ResolveError(err)),
+ Err(err) => Ok(MxDetails { lookup: Err(err) }),
}
}
diff --git a/core/src/smtp.rs b/core/src/smtp.rs
index dfcfd69e..d2001425 100644
--- a/core/src/smtp.rs
+++ b/core/src/smtp.rs
@@ -31,11 +31,13 @@ use serde::Serialize;
use std::time::Duration;
use trust_dns_resolver::Name;
-use super::util::email_input::EmailInputProxy;
+use super::util::{constants::LOG_TARGET, input_output::CheckEmailInputProxy};
/// Details that we gathered from connecting to this email via SMTP
#[derive(Debug, Serialize)]
pub struct SmtpDetails {
+ /// Are we able to connect to the SMTP server?
+ pub can_connect_smtp: bool,
/// Is this email account's inbox full?
pub has_full_inbox: bool,
/// Does this domain have a catch-all email address?
@@ -46,16 +48,26 @@ pub struct SmtpDetails {
pub is_disabled: bool,
}
-/// Error occured connecting to this email server via SMTP
+impl Default for SmtpDetails {
+ fn default() -> Self {
+ SmtpDetails {
+ can_connect_smtp: false,
+ has_full_inbox: false,
+ is_catch_all: false,
+ is_deliverable: false,
+ is_disabled: false,
+ }
+ }
+}
+
+/// Error occured connecting to this email server via SMTP.
#[derive(Debug, Serialize)]
#[serde(tag = "type", content = "message")]
pub enum SmtpError {
- /// Skipped checking SMTP details
- Skipped,
- /// Error if we're using a SOCKS5 proxy
+ /// Error if we're using a SOCKS5 proxy.
#[serde(serialize_with = "ser_with_display")]
SocksError(SocksError),
- /// Error when communicating with SMTP server
+ /// Error when communicating with SMTP server.
#[serde(serialize_with = "ser_with_display")]
SmtpError(AsyncSmtpError),
}
@@ -76,7 +88,7 @@ impl From<SocksError> for SmtpError {
macro_rules! try_smtp (
($res: expr, $client: ident, $host: expr, $port: expr) => ({
if let Err(err) = $res {
- debug!("Closing {}:{}, because of error '{}'.", $host, $port, err);
+ debug!(target: LOG_TARGET, "Closing {}:{}, because of error '{}'.", $host, $port, err);
$client.close().await?;
return Err(err.into());
@@ -84,13 +96,13 @@ macro_rules! try_smtp (
})
);
-/// Attempt to connect to host via SMTP, and return SMTP client on success
+/// Attempt to connect to host via SMTP, and return SMTP client on success.
async fn connect_to_host(
from_email: &EmailAddress,
host: &Name,
port: u16,
hello_name: &str,
- proxy: &Option<EmailInputProxy>,
+ proxy: &Option<CheckEmailInputProxy>,
) -> Result<SmtpTransport, SmtpError> {
let mut smtp_client =
SmtpClient::with_security((host.to_utf8().as_str(), port), ClientSecurity::None)
@@ -100,7 +112,7 @@ async fn connect_to_host(
.into_transport();
// Connect to the host. If the proxy argument is set, use it.
- debug!("Connecting to {}:{}", host, port);
+ debug!(target: LOG_TARGET, "Connecting to {}:{}", host, port);
if let Some(proxy) = proxy {
let stream = Socks5Stream::connect(
(proxy.host.as_ref(), proxy.port),
@@ -123,11 +135,10 @@ async fn connect_to_host(
}
// "MAIL FROM: [email protected]"
- // FIXME Do not clone?
- let from_email = from_email.clone();
try_smtp!(
smtp_client
- .command(MailCommand::new(Some(from_email), vec![],))
+ // FIXME Do not clone?
+ .command(MailCommand::new(Some(from_email.clone()), vec![],))
.await,
smtp_client,
host,
@@ -137,41 +148,37 @@ async fn connect_to_host(
Ok(smtp_client)
}
+/// Description of the deliverability information we can gather from
+/// communicating with the SMTP server.
struct Deliverability {
/// Is this email account's inbox full?
- pub has_full_inbox: bool,
+ has_full_inbox: bool,
/// Can we send an email to this address?
is_deliverable: bool,
/// Is the email blocked or disabled by the provider?
is_disabled: bool,
}
-/// Check if `to_email` exists on host server with given port
+/// Check if `to_email` exists on host SMTP server. This is the core logic of
+/// this tool.
async fn email_deliverable(
smtp_client: &mut SmtpTransport,
to_email: &EmailAddress,
) -> Result<Deliverability, SmtpError> {
// "RCPT TO: [email protected]"
// FIXME Do not clone?
- let to_email = to_email.clone();
match smtp_client
- .command(RcptCommand::new(to_email, vec![]))
+ .command(RcptCommand::new(to_email.clone(), vec![]))
.await
{
Ok(response) => match response.first_line() {
Some(message) => {
- if message.contains("2.1.5") {
- // 250 2.1.5 Recipient e-mail address ok.
- Ok(Deliverability {
- has_full_inbox: false,
- is_deliverable: true,
- is_disabled: false,
- })
- } else {
- Err(SmtpError::SmtpError(AsyncSmtpError::Client(
- "Can't find 2.1.5 in RCPT command",
- )))
- }
+ let is_deliverable = message.contains("2.1.5");
+ Ok(Deliverability {
+ has_full_inbox: false,
+ is_deliverable,
+ is_disabled: false,
+ })
}
None => Err(SmtpError::SmtpError(AsyncSmtpError::Client(
"No response on RCPT command",
@@ -180,9 +187,9 @@ async fn email_deliverable(
Err(err) => {
let err_string = err.to_string();
// Don't return an error if the error contains anything about the
- // address being undeliverable
+ // address being undeliverable.
- // Check if the email account has been disabled or blocked
+ // Check if the email account has been disabled or blocked.
// e.g. "The email account that you tried to reach is disabled. Learn more at https://support.google.com/mail/?p=DisabledUser"
if err_string.contains("disabled") || err_string.contains("blocked") {
return Ok(Deliverability {
@@ -192,7 +199,7 @@ async fn email_deliverable(
});
}
- // Check if the email account has a full inbox
+ // Check if the email account has a full inbox.
if err_string.contains("full")
|| err_string.contains("insufficient")
|| err_string.contains("over quota")
@@ -205,7 +212,7 @@ async fn email_deliverable(
});
}
- // These are the possible error messages when email account doesn't exist
+ // These are the possible error messages when email account doesn't exist.
if err_string.contains("address rejected")
|| err_string.contains("does not exist")
|| err_string.contains("invalid address")
@@ -216,7 +223,6 @@ async fn email_deliverable(
|| err_string.contains("undeliverable")
|| err_string.contains("user unknown")
|| err_string.contains("user not found")
- || err_string.contains("disabled")
{
return Ok(Deliverability {
has_full_inbox: false,
@@ -230,12 +236,12 @@ async fn email_deliverable(
}
}
-/// Verify the existence of a catch-all email
-async fn email_has_catch_all(
+/// Verify the existence of a catch-all on the domain.
+async fn smtp_is_catch_all(
smtp_client: &mut SmtpTransport,
domain: &str,
) -> Result<bool, SmtpError> {
- // Create a random 15-char alphanumerical string
+ // Create a random 15-char alphanumerical string.
let random_email = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(15)
@@ -250,19 +256,21 @@ async fn email_has_catch_all(
.map(|deliverability| deliverability.is_deliverable)
}
-/// Get all email details we can.
-pub async fn smtp_details(
- from_email: &EmailAddress,
+/// Get all email details we can from one single `EmailAddress`.
+pub async fn check_smtp(
to_email: &EmailAddress,
+ from_email: &EmailAddress,
host: &Name,
port: u16,
domain: &str,
hello_name: &str,
- proxy: &Option<EmailInputProxy>,
+ proxy: &Option<CheckEmailInputProxy>,
) -> Result<SmtpDetails, SmtpError> {
+ // FIXME If the SMTP is not connectable, we should actually return an
+ // Ok(SmtpDetails { can_connect_smtp: false, ... }).
let mut smtp_client = connect_to_host(from_email, host, port, hello_name, proxy).await?;
- let is_catch_all = email_has_catch_all(&mut smtp_client, domain)
+ let is_catch_all = smtp_is_catch_all(&mut smtp_client, domain)
.await
.unwrap_or(false);
let deliverability = email_deliverable(&mut smtp_client, to_email).await?;
@@ -270,6 +278,7 @@ pub async fn smtp_details(
smtp_client.close().await?;
Ok(SmtpDetails {
+ can_connect_smtp: true,
has_full_inbox: deliverability.has_full_inbox,
is_catch_all,
is_deliverable: deliverability.is_deliverable,
diff --git a/core/src/syntax.rs b/core/src/syntax.rs
index aeaead3a..c2e8b978 100644
--- a/core/src/syntax.rs
+++ b/core/src/syntax.rs
@@ -14,49 +14,50 @@
// You should have received a copy of the GNU General Public License
// along with check-if-email-exists. If not, see <http://www.gnu.org/licenses/>.
-use crate::util::ser_with_display::ser_with_display;
-use async_smtp::{error::Error as AsyncSmtpError, EmailAddress};
+use async_smtp::EmailAddress;
use serde::Serialize;
use std::str::FromStr;
/// Syntax information after parsing an email address
#[derive(Debug, PartialEq, Serialize)]
pub struct SyntaxDetails {
- /// The email address as a async_smtp EmailAddress
- pub address: EmailAddress,
- /// The domain name, after "@"
+ /// The email address as a async_smtp `EmailAddress`. It will be `None` if
+ /// the email address is ill-formed.
+ pub address: Option<EmailAddress>,
+ /// The domain name, after "@". It will be the empty string if the email
+ /// address if ill-formed.
pub domain: String,
/// Does the email have a valid syntax?
pub is_valid_syntax: bool,
- /// The username, before "@"
+ /// The username, before "@". It will be the empty string if the email
+ /// address if ill-formed.
pub username: String,
}
-#[derive(Debug, Serialize)]
-#[serde(tag = "type", content = "message")]
-pub enum SyntaxError {
- #[serde(serialize_with = "ser_with_display")]
- SyntaxError(AsyncSmtpError),
-}
-
-impl PartialEq for SyntaxError {
- fn eq(&self, other: &Self) -> bool {
- match (self, other) {
- (
- SyntaxError::SyntaxError(AsyncSmtpError::InvalidEmailAddress),
- SyntaxError::SyntaxError(AsyncSmtpError::InvalidEmailAddress),
- ) => true,
- _ => false,
+impl Default for SyntaxDetails {
+ fn default() -> Self {
+ SyntaxDetails {
+ address: None,
+ domain: "".into(),
+ is_valid_syntax: false,
+ username: "".into(),
}
}
}
/// From an `email_address` string, compute syntax information about it, such as
-/// username and domain
-pub fn address_syntax(email_address: &str) -> Result<SyntaxDetails, SyntaxError> {
+/// username and domain.
+pub fn check_syntax(email_address: &str) -> SyntaxDetails {
let email_address = match EmailAddress::from_str(email_address) {
Ok(m) => m,
- Err(error) => return Err(SyntaxError::SyntaxError(error)),
+ _ => {
+ return SyntaxDetails {
+ address: None,
+ domain: "".into(),
+ is_valid_syntax: false,
+ username: "".into(),
+ }
+ }
};
let iter: &str = email_address.as_ref();
@@ -70,14 +71,12 @@ pub fn address_syntax(email_address: &str) -> Result<SyntaxDetails, SyntaxError>
.expect("We checked above that email is valid. qed.")
.into();
- let address_details = SyntaxDetails {
- address: email_address,
+ SyntaxDetails {
+ address: Some(email_address),
domain,
is_valid_syntax: true,
username,
- };
-
- Ok(address_details)
+ }
}
#[cfg(test)]
@@ -85,35 +84,41 @@ mod tests {
use super::*;
#[test]
- fn should_return_error_for_invalid_email() {
+ fn should_return_invalid_for_invalid_email() {
assert_eq!(
- address_syntax("foo"),
- Err(SyntaxError::SyntaxError(
- AsyncSmtpError::InvalidEmailAddress
- ))
+ check_syntax("foo"),
+ SyntaxDetails {
+ address: None,
+ domain: "".into(),
+ is_valid_syntax: false,
+ username: "".into(),
+ }
);
}
#[test]
- fn should_return_error_for_invalid_email_with_at() {
+ fn should_return_invalid_for_invalid_email_with_at() {
assert_eq!(
- address_syntax("foo@bar"),
- Err(SyntaxError::SyntaxError(
- AsyncSmtpError::InvalidEmailAddress
- ))
+ check_syntax("foo@bar"),
+ SyntaxDetails {
+ address: None,
+ domain: "".into(),
+ is_valid_syntax: false,
+ username: "".into(),
+ }
);
}
#[test]
fn should_work_for_valid_email() {
assert_eq!(
- address_syntax("[email protected]"),
- Ok(SyntaxDetails {
- address: EmailAddress::new("[email protected]".into()).unwrap(),
+ check_syntax("[email protected]"),
+ SyntaxDetails {
+ address: Some(EmailAddress::new("[email protected]".into()).unwrap()),
domain: "bar.com".into(),
is_valid_syntax: true,
username: "foo".into(),
- })
+ }
);
}
}
diff --git a/core/src/util/constants.rs b/core/src/util/constants.rs
new file mode 100644
index 00000000..d86a3a6b
--- /dev/null
+++ b/core/src/util/constants.rs
@@ -0,0 +1,17 @@
+// check-if-email-exists
+// Copyright (C) 2018-2020 Amaury Martiny
+
+// check-if-email-exists is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// check-if-email-exists 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 General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with check-if-email-exists. If not, see <http://www.gnu.org/licenses/>.
+
+pub const LOG_TARGET: &str = "check-if-email-exists";
diff --git a/core/src/util/email_input.rs b/core/src/util/email_input.rs
deleted file mode 100644
index 05719dd8..00000000
--- a/core/src/util/email_input.rs
+++ /dev/null
@@ -1,75 +0,0 @@
-// check-if-email-exists
-// Copyright (C) 2018-2020 Amaury Martiny
-
-// check-if-email-exists is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// check-if-email-exists 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 General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with check-if-email-exists. If not, see <http://www.gnu.org/licenses/>.
-
-/// Perform the email verification via a specified proxy. The usage of a proxy
-/// is optional.
-pub struct EmailInputProxy {
- /// Use the specified SOCKS5 proxy host to perform email verification.
- pub host: String,
- /// Use the specified SOCKS5 proxy port to perform email verification.
- pub port: u16,
-}
-
-/// Builder pattern for the input argument into the main `email_exists`
-/// function.
-pub struct EmailInput {
- /// The email to validate.
- pub to_email: String,
- /// Email to use in the `MAIL FROM:` SMTP command.
- ///
- /// Defaults to "[email protected]".
- pub from_email: String,
- /// Name to use in the `EHLO:` SMTP command.
- ///
- /// Defaults to "localhost" (note: "localhost" is not a FQDN).
- pub hello_name: String,
- /// Perform the email verification via a specified proxy. The usage of a
- /// proxy is optional.
- pub proxy: Option<EmailInputProxy>,
-}
-
-impl EmailInput {
- /// Create a new EmailInput.
- pub fn new(email: String) -> EmailInput {
- EmailInput {
- to_email: email,
- from_email: "[email protected]".into(),
- hello_name: "localhost".into(),
- proxy: None,
- }
- }
-
- /// Set the email to use in the `MAIL FROM:` SMTP command.
- pub fn from_email(&mut self, email: String) -> &mut EmailInput {
- self.from_email = email;
- self
- }
-
- /// Set the name to use in the `EHLO:` SMTP command.
- pub fn hello_name(&mut self, name: String) -> &mut EmailInput {
- self.hello_name = name;
- self
- }
-
- /// Use the specified proxy to perform email verification.
- pub fn proxy(&mut self, proxy_host: String, proxy_port: u16) -> &mut EmailInput {
- self.proxy = Some(EmailInputProxy {
- host: proxy_host,
- port: proxy_port,
- });
- self
- }
-}
diff --git a/core/src/util/input_output.rs b/core/src/util/input_output.rs
new file mode 100644
index 00000000..977fff46
--- /dev/null
+++ b/core/src/util/input_output.rs
@@ -0,0 +1,141 @@
+// check-if-email-exists
+// Copyright (C) 2018-2020 Amaury Martiny
+
+// check-if-email-exists is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// check-if-email-exists 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 General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with check-if-email-exists. If not, see <http://www.gnu.org/licenses/>.
+
+use crate::misc::{MiscDetails, MiscError};
+use crate::mx::{MxDetails, MxError};
+use crate::smtp::{SmtpDetails, SmtpError};
+use crate::syntax::SyntaxDetails;
+use serde::{ser::SerializeMap, Serialize, Serializer};
+
+/// Perform the email verification via a specified proxy. The usage of a proxy
+/// is optional.
+#[derive(Debug, Clone)]
+pub struct CheckEmailInputProxy {
+ /// Use the specified SOCKS5 proxy host to perform email verification.
+ pub host: String,
+ /// Use the specified SOCKS5 proxy port to perform email verification.
+ pub port: u16,
+}
+
+/// Builder pattern for the input argument into the main `email_exists`
+/// function.
+#[derive(Debug, Clone)]
+pub struct CheckEmailInput {
+ /// The email to validate.
+ pub to_emails: Vec<String>,
+ /// Email to use in the `MAIL FROM:` SMTP command.
+ ///
+ /// Defaults to "[email protected]".
+ pub from_email: String,
+ /// Name to use in the `EHLO:` SMTP command.
+ ///
+ /// Defaults to "localhost" (note: "localhost" is not a FQDN).
+ pub hello_name: String,
+ /// Perform the email verification via a specified proxy. The usage of a
+ /// proxy is optional.
+ pub proxy: Option<CheckEmailInputProxy>,
+}
+
+impl CheckEmailInput {
+ /// Create a new CheckEmailInput.
+ pub fn new(to_emails: Vec<String>) -> CheckEmailInput {
+ CheckEmailInput {
+ to_emails,
+ from_email: "[email protected]".into(),
+ hello_name: "localhost".into(),
+ proxy: None,
+ }
+ }
+
+ /// Set the email to use in the `MAIL FROM:` SMTP command.
+ pub fn from_email(&mut self, email: String) -> &mut CheckEmailInput {
+ self.from_email = email;
+ self
+ }
+
+ /// Set the name to use in the `EHLO:` SMTP command.
+ pub fn hello_name(&mut self, name: String) -> &mut CheckEmailInput {
+ self.hello_name = name;
+ self
+ }
+
+ /// Use the specified proxy to perform email verification.
+ pub fn proxy(&mut self, proxy_host: String, proxy_port: u16) -> &mut CheckEmailInput {
+ self.proxy = Some(CheckEmailInputProxy {
+ host: proxy_host,
+ port: proxy_port,
+ });
+ self
+ }
+}
+
+/// The result of the [check_email](check_email) function.
+#[derive(Debug)]
+pub struct CheckEmailOutput {
+ /// Input by the user.
+ pub input: String,
+ /// Misc details about the email address.
+ pub misc: Result<MiscDetails, MiscError>,
+ /// Details about the MX host.
+ pub mx: Result<MxDetails, MxError>,
+ /// Details about the SMTP responses of the email.
+ pub smtp: Result<SmtpDetails, SmtpError>,
+ /// Details about the email address.
+ pub syntax: SyntaxDetails,
+}
+
+impl Default for CheckEmailOutput {
+ fn default() -> Self {
+ CheckEmailOutput {
+ input: String::default(),
+ misc: Ok(MiscDetails::default()),
+ mx: Ok(MxDetails::default()),
+ smtp: Ok(SmtpDetails::default()),
+ syntax: SyntaxDetails::default(),
+ }
+ }
+}
+
+// Implement a custom serialize.
+impl Serialize for CheckEmailOutput {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ // This is just used internally to get the nested error field.
+ #[derive(Serialize)]
+ struct MyError<E> {
+ error: E,
+ }
+
+ let mut map = serializer.serialize_map(Some(1))?;
+ map.serialize_entry("input", &self.input)?;
+ match &self.misc {
+ Ok(t) => map.serialize_entry("misc", &t)?,
+ Err(error) => map.serialize_entry("misc", &MyError { error })?,
+ }
+ match &self.mx {
+ Ok(t) => map.serialize_entry("mx", &t)?,
+ Err(error) => map.serialize_entry("mx", &MyError { error })?,
+ }
+ match &self.smtp {
+ Ok(t) => map.serialize_entry("smtp", &t)?,
+ Err(error) => map.serialize_entry("smtp", &MyError { error })?,
+ }
+ map.serialize_entry("syntax", &self.syntax)?;
+ map.end()
+ }
+}
diff --git a/core/src/util/mod.rs b/core/src/util/mod.rs
index d0293a1a..70ec06ed 100644
--- a/core/src/util/mod.rs
+++ b/core/src/util/mod.rs
@@ -14,5 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with check-if-email-exists. If not, see <http://www.gnu.org/licenses/>.
-pub mod email_input;
+pub mod constants;
+pub mod input_output;
pub mod ser_with_display;
diff --git a/core/src/util/ser_with_display.rs b/core/src/util/ser_with_display.rs
index 7c267368..2a16609b 100644
--- a/core/src/util/ser_with_display.rs
+++ b/core/src/util/ser_with_display.rs
@@ -17,7 +17,7 @@
use serde::Serializer;
use std::fmt::Display;
-/// Implement the `Serialize` trait for types that are `Display`
+/// Implement the `Serialize` trait for types that are `Display`.
/// https://stackoverflow.com/questions/58103801/serialize-using-the-display-trait
pub fn ser_with_display<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
diff --git a/src/cli.yml b/src/cli.yml
index 0a1e6ba2..b42348e0 100644
--- a/src/cli.yml
+++ b/src/cli.yml
@@ -31,7 +31,7 @@ args:
long: proxy-host
takes_value: true
- PROXY_PORT:
- default_value: '1080'
+ default_value: "1080"
help: Use the specified SOCKS5 proxy port to perform email verification. Only used when `--proxy-host` flag is set.
long: proxy-port
takes_value: true
diff --git a/src/http.rs b/src/http.rs
index 57f09d0d..e1485455 100644
--- a/src/http.rs
+++ b/src/http.rs
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with check-if-email-exists. If not, see <http://www.gnu.org/licenses/>.
-use check_if_email_exists::{email_exists, EmailInput};
+use check_if_email_exists::{check_email, CheckEmailInput};
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use serde::{Deserialize, Serialize};
@@ -25,8 +25,8 @@ use std::net::SocketAddr;
pub struct PostReqBody {
from_email: Option<String>,
hello_name: Option<String>,
- to_email: String,
- // TODO Add fields for proxy
+ to_email: Vec<String>,
+ // FIXME Add fields for proxy
}
/// Error Response from POST /
@@ -57,10 +57,10 @@ async fn req_handler(req: Request<Body>) -> Result<Response<Body>, hyper::Error>
};
// Create EmailInput from body
- let mut input = EmailInput::new(body.to_email);
+ let mut input = CheckEmailInput::new(body.to_email);
input.from_email(body.from_email.unwrap_or_else(|| "[email protected]".into())).hello_name(body.hello_name.unwrap_or_else(|| "localhost".into()));
- let body = email_exists(&input).await;
+ let body = check_email(&input).await;
let body = match serde_json::to_string(&body) {
Ok(b) => b,
Err(err) => {
diff --git a/src/main.rs b/src/main.rs
index 75116fa1..3542ca69 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -22,7 +22,7 @@ extern crate tokio;
mod http;
-use check_if_email_exists::{email_exists, EmailInput};
+use check_if_email_exists::{check_email, CheckEmailInput};
use clap::{crate_version, value_t, App};
use std::env;
@@ -42,7 +42,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
.value_of("HELLO_NAME")
.expect("HELLO_NAME has a default value. qed.");
- let mut input = EmailInput::new(to_email.into());
+ let mut input = CheckEmailInput::new(vec![to_email.into()]);
input
.from_email(from_email.into())
.hello_name(hello_name.into());
@@ -53,7 +53,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
input.proxy(proxy_host.into(), proxy_port);
}
- let result = email_exists(&input).await;
+ let result = check_email(&input).await;
match serde_json::to_string_pretty(&result) {
Ok(output) => {
diff --git a/test_suite/Cargo.toml b/test_suite/Cargo.toml
index 9ed289d9..4047601e 100644
--- a/test_suite/Cargo.toml
+++ b/test_suite/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "check-if-email-exists-test-suite"
-version = "0.7.1"
+version = "0.8.0"
edition = "2018"
publish = false
diff --git a/test_suite/src/fixtures/foo.json b/test_suite/src/fixtures/foo.json
new file mode 100644
index 00000000..aa2e664a
--- /dev/null
+++ b/test_suite/src/fixtures/foo.json
@@ -0,0 +1,18 @@
+{
+ "input": "foo",
+ "misc": { "is_disposable": false },
+ "mx": { "accepts_mail": false, "records": [] },
+ "smtp": {
+ "can_connect_smtp": false,
+ "has_full_inbox": false,
+ "is_catch_all": false,
+ "is_deliverable": false,
+ "is_disabled": false
+ },
+ "syntax": {
+ "address": null,
+ "domain": "",
+ "is_valid_syntax": false,
+ "username": ""
+ }
+}
diff --git a/test_suite/src/fixtures/[email protected] b/test_suite/src/fixtures/[email protected]
new file mode 100644
index 00000000..013cbe12
--- /dev/null
+++ b/test_suite/src/fixtures/[email protected]
@@ -0,0 +1,18 @@
+{
+ "input": "[email protected]",
+ "misc": { "is_disposable": false },
+ "mx": { "accepts_mail": false, "records": [] },
+ "smtp": {
+ "can_connect_smtp": false,
+ "has_full_inbox": false,
+ "is_catch_all": false,
+ "is_deliverable": false,
+ "is_disabled": false
+ },
+ "syntax": {
+ "address": "[email protected]",
+ "domain": "bar.baz",
+ "is_valid_syntax": true,
+ "username": "foo"
+ }
+}
diff --git a/test_suite/src/fixtures/[email protected] b/test_suite/src/fixtures/[email protected]
new file mode 100644
index 00000000..764d0b05
--- /dev/null
+++ b/test_suite/src/fixtures/[email protected]
@@ -0,0 +1,18 @@
+{
+ "input": "foo@bar",
+ "misc": { "is_disposable": false },
+ "mx": { "accepts_mail": false, "records": [] },
+ "smtp": {
+ "can_connect_smtp": false,
+ "has_full_inbox": false,
+ "is_catch_all": false,
+ "is_deliverable": false,
+ "is_disabled": false
+ },
+ "syntax": {
+ "address": null,
+ "domain": "",
+ "is_valid_syntax": false,
+ "username": ""
+ }
+}
diff --git a/test_suite/src/fixtures/[email protected] b/test_suite/src/fixtures/[email protected]
new file mode 100644
index 00000000..5eaa7e85
--- /dev/null
+++ b/test_suite/src/fixtures/[email protected]
@@ -0,0 +1,27 @@
+{
+ "input": "[email protected]",
+ "misc": { "is_disposable": false },
+ "mx": {
+ "accepts_mail": true,
+ "records": [
+ "alt4.gmail-smtp-in.l.google.com.",
+ "alt1.gmail-smtp-in.l.google.com.",
+ "alt2.gmail-smtp-in.l.google.com.",
+ "gmail-smtp-in.l.google.com.",
+ "alt3.gmail-smtp-in.l.google.com."
+ ]
+ },
+ "smtp": {
+ "can_connect_smtp": true,
+ "has_full_inbox": false,
+ "is_catch_all": false,
+ "is_deliverable": false,
+ "is_disabled": true
+ },
+ "syntax": {
+ "address": "[email protected]",
+ "domain": "gmail.com",
+ "is_valid_syntax": true,
+ "username": "someone"
+ }
+}
diff --git a/test_suite/src/lib.rs b/test_suite/src/lib.rs
index 65901193..63570c9c 100644
--- a/test_suite/src/lib.rs
+++ b/test_suite/src/lib.rs
@@ -18,30 +18,84 @@
#[cfg(test)]
mod tests {
- use check_if_email_exists::{email_exists, EmailInput};
+ use check_if_email_exists::{check_email, CheckEmailInput};
+ use serde_json;
+ use std::fs;
use tokio::runtime::Runtime;
+ /// Function to test all fixtures from a folder.
+ fn test_all_from_folder(folder: &str) {
+ let mut runtime = Runtime::new().unwrap();
+ let paths = fs::read_dir(folder).unwrap();
+
+ // For every fixture file, we compare:
+ // - the result of `check_email` with the email in the filename
+ // - the contents of the file
+ for path in paths {
+ let path = path.unwrap().path();
+ let file = fs::File::open(path.clone()).unwrap();
+ let filename = path.file_stem().unwrap().to_str().unwrap();
+ if filename.starts_with(".") {
+ // Don't process hidden files.
+ continue;
+ }
+ let expected: serde_json::Value = serde_json::from_reader(file).unwrap();
+
+ println!("Check {}", filename);
+ let input = CheckEmailInput::new(vec![filename.into()]);
+ let result = runtime.block_on(check_email(&input));
+ let actual = serde_json::to_value(&result[0]).unwrap();
+
+ // Uncomment to see the JSON result of `check_email`.
+ // println!("{}", actual);
+
+ // For the input,misc,smtp,syntax fields, we match exact JSON.
+ assert_eq!(expected.get("input"), actual.get("input"),);
+ assert_eq!(expected.get("misc"), actual.get("misc"),);
+ assert_eq!(expected.get("smtp"), actual.get("smtp"),);
+ assert_eq!(expected.get("syntax"), actual.get("syntax"),);
+
+ // For the mx field, the `records` field array can contain elements
+ // in different order. We only check length in that case
+ if expected.get("mx").unwrap().get("error").is_some() {
+ assert_eq!(expected.get("mx"), actual.get("mx"));
+ } else {
+ assert_eq!(
+ expected.get("mx").unwrap().get("accepts_mail"),
+ actual.get("mx").unwrap().get("accepts_mail")
+ );
+
+ assert_eq!(
+ expected
+ .get("mx")
+ .unwrap()
+ .get("records")
+ .unwrap()
+ .as_array()
+ .unwrap()
+ .len(),
+ actual
+ .get("mx")
+ .unwrap()
+ .get("records")
+ .unwrap()
+ .as_array()
+ .unwrap()
+ .len()
+ );
+ }
+ }
+ }
+
#[test]
- fn should_output_error_for_invalid_email() {
- let result = Runtime::new()
- .unwrap()
- .block_on(email_exists(&EmailInput::new("foo".to_string())));
- assert_eq!(
- serde_json::to_string(&result).unwrap(),
- "{\"input\":\"foo\",\"misc\":{\"error\":{\"type\":\"Skipped\"}},\"mx\":{\"error\":{\"type\":\"Skipped\"}},\"smtp\":{\"error\":{\"type\":\"Skipped\"}},\"syntax\":{\"error\":{\"type\":\"SyntaxError\",\"message\":\"invalid email address\"}}}"
- );
+ fn should_pass_fixtures() {
+ test_all_from_folder("./src/fixtures");
}
- /// Note: this test requires an internet connection.
#[test]
- fn should_output_error_for_invalid_mx() {
- let result = Runtime::new()
- .unwrap()
- .block_on(email_exists(&EmailInput::new("[email protected]".to_string())));
-
- assert_eq!(
- serde_json::to_string(&result).unwrap(),
- "{\"input\":\"[email protected]\",\"misc\":{\"error\":{\"type\":\"Skipped\"}},\"mx\":{\"error\":{\"type\":\"ResolveError\",\"message\":\"no record found for name: bar.baz type: MX class: IN\"}},\"smtp\":{\"error\":{\"type\":\"Skipped\"}},\"syntax\":{\"address\":\"[email protected]\",\"domain\":\"bar.baz\",\"is_valid_syntax\":true,\"username\":\"foo\"}}"
- );
+ fn should_pass_sensitive_fixtures() {
+ // These fixtures contain real-file emails, they are not committed to
+ // git.
+ test_all_from_folder("./src/sensitive_fixtures");
}
}
diff --git a/test_suite/src/sensitive_fixtures/.gitkeep b/test_suite/src/sensitive_fixtures/.gitkeep
new file mode 100644
index 00000000..e69de29b