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: Use builder pattern for EmailInput (#254)
Amaury Martiny0c85d36cdccb
diff --git a/Cargo.lock b/Cargo.lockindex 56cf1615..2adecaef 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -205,7 +205,7 @@ checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"[[package]]name = "check-if-email-exists"-version = "0.6.7"+version = "0.7.0"dependencies = ["async-smtp","futures",@@ -219,7 +219,7 @@ dependencies = [[[package]]name = "check-if-email-exists-cli"-version = "0.6.7"+version = "0.7.0"dependencies = ["check-if-email-exists","clap",@@ -232,7 +232,7 @@ dependencies = [[[package]]name = "check-if-email-exists-test-suite"-version = "0.6.7"+version = "0.7.0"dependencies = ["check-if-email-exists","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 206629bb..279c35ce 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check-if-email-exists-cli"-version = "0.6.7"+version = "0.7.0"default-run = "check_if_email_exists"edition = "2018"publish = falsediff --git a/Dockerfile b/Dockerfileindex a2bc0ec0..403965ef 100644--- a/Dockerfile+++ b/Dockerfile@@ -3,7 +3,7 @@ FROM alpine# `ciee` stands for check-if-email-existsWORKDIR /ciee# Fetch latest version-ENV CIEE_VERSION 0.6.7+ENV CIEE_VERSION 0.7.0# Install needed librariesRUN apk update && \diff --git a/README.md b/README.mdindex 3ba698f9..5dba1e85 100644--- a/README.md+++ b/README.md@@ -67,11 +67,10 @@ To run it, run the following command:docker run -p 3000:3000 amaurymartiny/check-if-email-exists```-You can then send a POST request with the following body (`from_email` is optional) to `http://localhost:3000`:+You can then send a POST request with the following body to `http://localhost:3000`:```json{- "from_email": "[email protected]","to_email": "[email protected]"}```@@ -79,9 +78,11 @@ You can then send a POST request with the following body (`from_email` is optionHere's the equivalent `curl` command:```bash-curl -X POST -d'{"from_email":"[email protected]","to_email":"[email protected]"}' http://localhost:3000+curl -X POST -d'{"to_email":"[email protected]"}' http://localhost:3000```+Optionally, you can also pass in `from_email` and `hello_name` fields into the JSON object, see the help message below to understand their meanings.+### 3. Download the Binary> Note: The binary doesn't connect to any backend, it checks the email directly from your computer.@@ -90,33 +91,33 @@ Head to the [releases page](https://github.com/amaurymartiny/check-if-email-exis```> $ check_if_email_exists --help-check_if_email_exists 0.6.7+check_if_email_exists 0.7.0Check if an email address exists without sending any email.USAGE:check_if_email_exists [FLAGS] [OPTIONS] [TO_EMAIL]FLAGS:- --http Runs a HTTP server+ --http Runs a HTTP server.-h, --help Prints help information-V, --version Prints version informationOPTIONS:- --from <FROM_EMAIL> The from email to use in the SMTP connection [default: [email protected]]- --http-host <HOST> Sets the host IP address on which the HTTP server should bind. Only used when `--http`- flag is on [default: 127.0.0.1]- --http-port <PORT> Sets the port on which the HTTP server should bind. Only used when `--http` flag is on- [default: 3000]+ --from-email <FROM_EMAIL> The email to use in the `MAIL FROM:` SMTP command. [default: [email protected]]+ --hello-name <HELLO_NAME> The name to use in the `EHLO:` SMTP command. [default: localhost]+ --http-host <HOST> Sets the host IP address on which the HTTP server should bind. Only used when+ `--http` flag is on. [default: 127.0.0.1]+ --http-port <PORT> Sets the port on which the HTTP server should bind. Only used when `--http` flag is+ on. If not set, then it will use $PORT, or default to 3000.ARGS:- <TO_EMAIL> The email to check+ <TO_EMAIL> The email to check.```-If you run with the `--http` flag, `check-if-email-exists` will serve a HTTP server on `http://localhost:3000`. You can then send a POST request with the following body (`from_email` is optional):+If you run with the `--http` flag, `check-if-email-exists` will serve a HTTP server on `http://localhost:3000`. You can then send a POST request with the following body:```json{- "from_email": "[email protected]","to_email": "[email protected]"}```@@ -124,16 +125,18 @@ If you run with the `--http` flag, `check-if-email-exists` will serve a HTTP serHere's the equivalent `curl` command:```bash-curl -X POST -d'{"from_email":"[email protected]","to_email":"[email protected]"}' http://localhost:3000+curl -X POST -d'{"to_email":"[email protected]"}' http://localhost:3000```+Optionally, you can also pass in `from_email` and `hello_name` fields into the JSON object, see the help message above to understand their meanings.+**💡 PRO TIP:** To show debug logs when running the binary, run:```bashRUST_LOG=debug check_if_email_exists [FLAGS] [OPTIONS] [TO_EMAIL]```-### 4. Usage as a Library (Advanced)+### 4. Usage as a Rust LibraryIn your own Rust project, you can add `check-if-email-exists` in your `Cargo.toml`:@@ -145,7 +148,6 @@ check-if-email-exists = "0.6"And use it in your code as follows (async/await syntax):```rust-use check_if_email_exists::email_exists;// First arg is the email we want to check, second arg is the FROM email used in the SMTP connectiondiff --git a/core/Cargo.toml b/core/Cargo.tomlindex e53cdd61..cb9db281 100644--- a/core/Cargo.toml+++ b/core/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check-if-email-exists"-version = "0.6.7"+version = "0.7.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.rsindex 1514e727..5b3c5939 100644--- a/core/src/lib.rs+++ b/core/src/lib.rs@@ -37,6 +37,8 @@ use smtp::{SmtpDetails, SmtpError};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 {@@ -88,17 +90,21 @@ impl Serialize for SingleEmail {/// The main function: checks email format, checks MX records, and checks SMTP/// responses to the email inbox.-pub async fn email_exists(to_email: &str, from_email: &str) -> SingleEmail {- let from_email = EmailAddress::from_str(from_email).unwrap_or_else(|_| {+pub async fn email_exists(email_input: &EmailInput) -> SingleEmail {+ let from_email = EmailAddress::from_str(email_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+ );EmailAddress::from_str("[email protected]").expect("This is a valid email. qed.")});- debug!("Checking email \"{}\"", to_email);- let my_syntax = match address_syntax(to_email) {+ 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: to_email.into(),+ input: email_input.to_email.to_string(),misc: Err(MiscError::Skipped),mx: Err(MxError::Skipped),smtp: Err(SmtpError::Skipped),@@ -112,7 +118,7 @@ pub async fn email_exists(to_email: &str, from_email: &str) -> SingleEmail {Ok(m) => m,e => {return SingleEmail {- input: to_email.into(),+ input: email_input.to_email.to_string(),misc: Err(MiscError::Skipped),mx: e,smtp: Err(SmtpError::Skipped),@@ -137,6 +143,7 @@ pub async fn email_exists(to_email: &str, from_email: &str) -> SingleEmail {// We could add ports 465 and 587 tooSMTP_PORT,my_syntax.domain.as_str(),+ email_input.hello_name.as_ref(),);// https://rust-lang.github.io/async-book/04_pinning/01_chapter.html@@ -151,7 +158,7 @@ pub async fn email_exists(to_email: &str, from_email: &str) -> SingleEmail {};SingleEmail {- input: to_email.into(),+ input: email_input.to_email.to_string(),misc: Ok(my_misc),mx: Ok(my_mx),smtp: my_smtp,diff --git a/core/src/mx.rs b/core/src/mx.rsindex 4276641f..2ea9aa26 100644--- a/core/src/mx.rs+++ b/core/src/mx.rs@@ -15,7 +15,7 @@// along with check-if-email-exists. If not, see <http://www.gnu.org/licenses/>.use crate::syntax::SyntaxDetails;-use crate::util::ser_with_display;+use crate::util::ser_with_display::ser_with_display;use serde::{ser::SerializeMap, Serialize, Serializer};use std::io::Error;use trust_dns_resolver::{config::*, error::ResolveError, lookup::MxLookup, TokioAsyncResolver};diff --git a/core/src/smtp.rs b/core/src/smtp.rsindex 664c5d01..2b48b61b 100644--- a/core/src/smtp.rs+++ b/core/src/smtp.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 crate::util::ser_with_display;+use crate::util::ser_with_display::ser_with_display;use async_smtp::{smtp::{commands::*, error::Error as AsyncSmtpError, extension::ClientId},ClientSecurity, EmailAddress, SmtpClient, SmtpTransport,@@ -71,12 +71,13 @@ async fn connect_to_host(from_email: &EmailAddress,host: &Name,port: u16,+ hello_name: &str,) -> Result<SmtpTransport, AsyncSmtpError> {debug!("Connecting to {}:{}", host, port);let mut smtp_client =SmtpClient::with_security((host.to_utf8().as_str(), port), ClientSecurity::None).await?- .hello_name(ClientId::Domain("localhost".into()))+ .hello_name(ClientId::Domain(hello_name.into())).timeout(Some(Duration::new(30, 0))) // Set timeout to 30s.into_transport();@@ -218,8 +219,9 @@ pub async fn smtp_details(host: &Name,port: u16,domain: &str,+ hello_name: &str,) -> Result<SmtpDetails, SmtpError> {- let mut smtp_client = connect_to_host(from_email, host, port).await?;+ let mut smtp_client = connect_to_host(from_email, host, port, hello_name).await?;let is_catch_all = email_has_catch_all(&mut smtp_client, domain).awaitdiff --git a/core/src/syntax.rs b/core/src/syntax.rsindex b898d473..e2178320 100644--- a/core/src/syntax.rs+++ b/core/src/syntax.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 crate::util::ser_with_display;+use crate::util::ser_with_display::ser_with_display;use async_smtp::{error::Error as AsyncSmtpError, EmailAddress};use serde::Serialize;use std::str::FromStr;diff --git a/core/src/util/email_input.rs b/core/src/util/email_input.rsnew file mode 100644index 00000000..dcfa85ad--- /dev/null+++ b/core/src/util/email_input.rs@@ -0,0 +1,51 @@+// 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/>.++/// 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,+}++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(),+ }+ }++ /// 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+ }+}diff --git a/core/src/util/mod.rs b/core/src/util/mod.rsindex 7c267368..d0293a1a 100644--- a/core/src/util/mod.rs+++ b/core/src/util/mod.rs@@ -14,15 +14,5 @@// 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 serde::Serializer;-use std::fmt::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- T: Display,- S: Serializer,-{- serializer.collect_str(value)-}+pub mod email_input;+pub mod ser_with_display;diff --git a/core/src/util/ser_with_display.rs b/core/src/util/ser_with_display.rsnew file mode 100644index 00000000..7c267368--- /dev/null+++ b/core/src/util/ser_with_display.rs@@ -0,0 +1,28 @@+// 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 serde::Serializer;+use std::fmt::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+ T: Display,+ S: Serializer,+{+ serializer.collect_str(value)+}diff --git a/src/cli.yml b/src/cli.ymlindex 8f0cf29e..b8371e94 100644--- a/src/cli.yml+++ b/src/cli.yml@@ -4,8 +4,13 @@ about: Check if an email address exists without sending any email.args:- FROM_EMAIL:default_value: [email protected]- long: from- help: The from email to use in the SMTP connection.+ long: from-email+ help: The email to use in the `MAIL FROM:` SMTP command.+ takes_value: true+ - HELLO_NAME:+ default_value: localhost+ long: hello-name+ help: The name to use in the `EHLO:` SMTP command.takes_value: true- HTTP:long: httpdiff --git a/src/http.rs b/src/http.rsindex d90d6f7d..eac0a4d0 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;+use check_if_email_exists::{email_exists, EmailInput};use hyper::service::{make_service_fn, service_fn};use hyper::{Body, Method, Request, Response, Server, StatusCode};use serde::{Deserialize, Serialize};@@ -24,6 +24,7 @@ use std::net::SocketAddr;#[derive(Debug, Deserialize, Serialize)]pub struct PostReqBody {from_email: Option<String>,+ hello_name: Option<String>,to_email: String,}@@ -36,7 +37,7 @@ async fn req_handler(req: Request<Body>) -> Result<Response<Body>, hyper::Error>match (req.method(), req.uri().path()) {// Serve some instructions at /(&Method::GET, "/") => Ok(Response::new(Body::from(- "Send a POST request with JSON `{ \"from_email\": \"<email>\", to_email: \"<email>\" }` in the body",+ "Send a POST request with JSON `{ \"from_email\"?: \"<email>\", \"hello_name\"?: \"<name>\", to_email: \"<email>\" }` in the body",))),// Do email_exists check on POST /@@ -54,10 +55,11 @@ async fn req_handler(req: Request<Body>) -> Result<Response<Body>, hyper::Error>}};- let body = email_exists(- &body.to_email,- &body.from_email.unwrap_or_else(|| "[email protected]".into()),- ).await;+ // Create EmailInput from body+ let mut input = EmailInput::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 = match serde_json::to_string(&body) {Ok(b) => b,Err(err) => {diff --git a/src/main.rs b/src/main.rsindex e390c592..90eaf6d0 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;+use check_if_email_exists::{email_exists, EmailInput};use clap::{crate_version, App};use serde_json;use std::env;@@ -39,8 +39,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {let from_email = matches.value_of("FROM_EMAIL").expect("FROM_EMAIL has a default value. qed.");+ let hello_name = matches+ .value_of("HELLO_NAME")+ .expect("HELLO_NAME has a default value. qed.");- let result = email_exists(&to_email, &from_email).await;+ let result = email_exists(+ EmailInput::new(to_email.into())+ .from_email(from_email.into())+ .hello_name(hello_name.into()),+ )+ .await;match serde_json::to_string_pretty(&result) {Ok(output) => {diff --git a/test_suite/Cargo.toml b/test_suite/Cargo.tomlindex eac95cf5..91c58389 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.6.7"+version = "0.7.0"edition = "2018"publish = falsediff --git a/test_suite/src/lib.rs b/test_suite/src/lib.rsindex 6a329e8b..a6f31bb0 100644--- a/test_suite/src/lib.rs+++ b/test_suite/src/lib.rs@@ -18,25 +18,26 @@#[cfg(test)]mod tests {- use check_if_email_exists::email_exists;+ use check_if_email_exists::{email_exists, EmailInput};use tokio::runtime::Runtime;#[test]fn should_output_error_for_invalid_email() {let result = Runtime::new().unwrap()- .block_on(email_exists("foo", "[email protected]"));+ .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\"}}}");}+ /// Note: this test requires an internet connection.#[test]fn should_output_error_for_invalid_mx() {let result = Runtime::new().unwrap()- .block_on(email_exists("[email protected]", "[email protected]"));+ .block_on(email_exists(&EmailInput::new("[email protected]".to_string())));assert_eq!(serde_json::to_string(&result).unwrap(),