Check if an email address exists without sending any email, written in Rust. Comes with a ⚙️ HTTP backend.
Rust emailemail-validationemail-validation-apiemail-verificationemail-verification-apiemail-verifierhacktoberfest
feat: Add disposable email check (#64)
Amaury Martiny1b2cea3a6ffe
diff --git a/Cargo.lock b/Cargo.lockindex 90e047f8..46fc7a47 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -119,9 +119,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"[[package]]name = "check_if_email_exists"-version = "0.3.2"+version = "0.4.0"dependencies = [- "check_if_email_exists_core 0.3.2",+ "check_if_email_exists_core 0.4.0","clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)","env_logger 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)","serde 1.0.101 (registry+https://github.com/rust-lang/crates.io-index)",@@ -130,10 +130,11 @@ dependencies = [[[package]]name = "check_if_email_exists_core"-version = "0.3.2"+version = "0.4.0"dependencies = ["lettre 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)","log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",+ "mailchecker 3.2.35 (registry+https://github.com/rust-lang/crates.io-index)","native-tls 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)","rand 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)","rayon 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)",@@ -144,9 +145,9 @@ dependencies = [[[package]]name = "check_if_email_exists_serverless"-version = "0.3.2"+version = "0.4.0"dependencies = [- "check_if_email_exists_core 0.3.2",+ "check_if_email_exists_core 0.4.0","lambda_http 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)","lambda_runtime 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)","serde 1.0.101 (registry+https://github.com/rust-lang/crates.io-index)",@@ -155,9 +156,9 @@ dependencies = [[[package]]name = "check_if_email_exists_test_suite"-version = "0.3.2"+version = "0.4.0"dependencies = [- "check_if_email_exists_core 0.3.2",+ "check_if_email_exists_core 0.4.0","serde 1.0.101 (registry+https://github.com/rust-lang/crates.io-index)","serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",]@@ -665,6 +666,14 @@ dependencies = ["linked-hash-map 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)",]+[[package]]+name = "mailchecker"+version = "3.2.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+dependencies = [+ "fast_chemail 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)",+]+[[package]]name = "matches"version = "0.1.8"@@ -1751,6 +1760,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index""checksum lock_api 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c""checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7""checksum lru-cache 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c"+"checksum mailchecker 3.2.35 (registry+https://github.com/rust-lang/crates.io-index)" = "fb9afee880495a318a969aff310e081614a6c229d10bd0ab73d7ca78ae9b6437""checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08""checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e""checksum memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3"diff --git a/Cargo.toml b/Cargo.tomlindex 1c4d9e56..c270596b 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check_if_email_exists"-version = "0.3.2"+version = "0.4.0"authors = ["Amaury Martiny <[email protected]>"]description = "Check if an email address exists without sending any email"edition = "2018"diff --git a/README.md b/README.mdindex a69f5917..598e3736 100644--- a/README.md+++ b/README.md@@ -47,6 +47,7 @@ The output will be a JSON with the following format, for `[email protected]` (no```json{"mx": {+ "is_disposable": false,"records": ["alt3.gmail-smtp-in.l.google.com.","gmail-smtp-in.l.google.com.",@@ -56,9 +57,10 @@ The output will be a JSON with the following format, for `[email protected]` (no]},"smtp": {- "deliverable": false,- "full_inbox": false,- "has_catch_all": false+ "has_full_inbox": false,+ "is_catch_all": false,+ "is_deliverable": false,+ "is_disabled": true,},"syntax": {"address": "[email protected]",diff --git a/ci/script.sh b/ci/script.shindex 9f3a011e..6318df94 100755--- a/ci/script.sh+++ b/ci/script.sh@@ -18,8 +18,8 @@ main() {# aka some quick e2e test on the binary itself# TODO This only works on osx now, see #11if [ $TRAVIS_OS_NAME = osx ]; then- cross run --target $TARGET $TEST_EMAIL | grep "\"deliverable\": true"- cross run --target $TARGET --release $TEST_EMAIL | grep "\"deliverable\": true"+ cross run --target $TARGET $TEST_EMAIL | grep "\"is_deliverable\": true"+ cross run --target $TARGET --release $TEST_EMAIL | grep "\"is_deliverable\": true"fi}diff --git a/core/Cargo.toml b/core/Cargo.tomlindex a86b5e73..c962a848 100644--- a/core/Cargo.toml+++ b/core/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check_if_email_exists_core"-version = "0.3.2"+version = "0.4.0"authors = ["Amaury Martiny <[email protected]>"]description = "Check if an email address exists without sending any email"edition = "2018"@@ -9,6 +9,7 @@ publish = false[dependencies]lettre = "0.9"log = "0.4"+mailchecker = "3.2"native-tls = "^0.2"rand = "0.7"rayon = "1.2.0"diff --git a/core/src/lib.rs b/core/src/lib.rsindex bbbafa3d..c3f7b6ad 100644--- a/core/src/lib.rs+++ b/core/src/lib.rs@@ -17,6 +17,7 @@extern crate lettre;#[macro_use]extern crate log;+extern crate mailchecker;extern crate native_tls;extern crate rand;extern crate rayon;@@ -97,7 +98,7 @@ pub fn email_exists(to_email: &str, from_email: &str) -> SingleEmail {debug!("Details of the email address: {:?}", my_syntax);debug!("Getting MX lookup...");- let my_mx = match get_mx_lookup(&my_syntax.domain) {+ let my_mx = match get_mx_lookup(&my_syntax) {Ok(m) => m,e => {return SingleEmail {@@ -112,7 +113,7 @@ pub fn email_exists(to_email: &str, from_email: &str) -> SingleEmail {// `(host, port)` combination// We could add ports 465 and 587 toolet combinations = my_mx- .0+ .lookup.iter().map(|host| (host.exchange(), SMTP_PORT)).collect::<Vec<_>>();diff --git a/core/src/mx.rs b/core/src/mx.rsindex 345deb79..884f9b9b 100644--- a/core/src/mx.rs+++ b/core/src/mx.rs@@ -14,7 +14,9 @@// 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 crate::util::ser_with_display;+use mailchecker;use serde::{ser::SerializeMap, Serialize, Serializer};use std::io::Error;use trust_dns_resolver::config::*;@@ -24,7 +26,10 @@ use trust_dns_resolver::Resolver;/// Details about the MX lookup#[derive(Debug)]-pub struct MxDetails(pub MxLookup);+pub struct MxDetails {+ pub is_disposable: bool,+ pub lookup: MxLookup,+}impl Serialize for MxDetails {fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>@@ -35,11 +40,12 @@ impl Serialize for MxDetails {map.serialize_entry("records",&self- .0+ .lookup.iter().map(|host| host.exchange().to_string()).collect::<Vec<_>>(),)?;+ map.serialize_entry("is_disposable", &self.is_disposable)?;map.end()}}@@ -59,7 +65,7 @@ pub enum MxError {}/// Make a MX lookup-pub fn get_mx_lookup(domain: &str) -> Result<MxDetails, MxError> {+pub fn get_mx_lookup(syntax: &SyntaxDetails) -> Result<MxDetails, MxError> {// Construct a new Resolver with default configuration optionslet resolver = match Resolver::new(ResolverConfig::default(), ResolverOpts::default()) {Ok(r) => r,@@ -71,8 +77,14 @@ pub fn get_mx_lookup(domain: &str) -> Result<MxDetails, MxError> {// Lookup the MX records associated with a name.// The final dot forces this to be an FQDN, otherwise the search rules as specified// in `ResolverOpts` will take effect. FQDN's are generally cheaper queries.- match resolver.mx_lookup(domain) {- Ok(lookup) => Ok(MxDetails(lookup)),+ match resolver.mx_lookup(syntax.domain.as_ref()) {+ Ok(lookup) => Ok(MxDetails {+ // 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 provider.+ is_disposable: !mailchecker::is_valid(syntax.address.to_string().as_ref()),+ lookup,+ }),Err(err) => Err(MxError::ResolveError(err)),}}diff --git a/core/src/smtp.rs b/core/src/smtp.rsindex bef5630a..793d3613 100644--- a/core/src/smtp.rs+++ b/core/src/smtp.rs@@ -30,12 +30,14 @@ use trust_dns_resolver::Name;/// Details that we gathered from connecting to this email via SMTP#[derive(Debug, Serialize)]pub struct SmtpDetails {- /// Can we send an email to this address?- pub deliverable: bool,/// Is this email account's inbox full?- pub full_inbox: bool,+ pub has_full_inbox: bool,/// Does this domain have a catch-all email address?- pub has_catch_all: bool,+ pub is_catch_all: bool,+ /// Can we send an email to this address?+ pub is_deliverable: bool,+ /// Is the email blocked or disabled by the provider?+ pub is_disabled: bool,}/// Error occured connecting to this email server via SMTP@@ -108,11 +110,20 @@ fn connect_to_host(Ok(smtp_client)}+struct Deliverability {+ /// Is this email account's inbox full?+ pub 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 portfn email_deliverable(smtp_client: &mut InnerClient<NetworkStream>,to_email: &EmailAddress,-) -> Result<bool, LettreSmtpError> {+) -> Result<Deliverability, LettreSmtpError> {// "RCPT TO: [email protected]"// FIXME Do not clone?let to_email = to_email.clone();@@ -121,7 +132,11 @@ fn email_deliverable(Some(message) => {if message.contains("2.1.5") {// 250 2.1.5 Recipient e-mail address ok.- Ok(true)+ Ok(Deliverability {+ has_full_inbox: false,+ is_deliverable: true,+ is_disabled: false,+ })} else {Err(LettreSmtpError::Client("Can't find 2.1.5 in RCPT command"))}@@ -132,6 +147,31 @@ fn email_deliverable(let err_string = err.to_string();// Don't return an error if the error contains anything about the// address being undeliverable++ // 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 {+ has_full_inbox: false,+ is_deliverable: false,+ is_disabled: true,+ });+ }++ // Check if the email account has a full inbox+ if err_string.contains("full")+ || err_string.contains("insufficient")+ || err_string.contains("over quota")+ || err_string.contains("space")+ {+ return Ok(Deliverability {+ has_full_inbox: true,+ is_deliverable: false,+ is_disabled: false,+ });+ }++ // These are the possible error messages when email account doesn't existif err_string.contains("address rejected")|| err_string.contains("does not exist")|| err_string.contains("invalid address")@@ -142,13 +182,16 @@ fn email_deliverable(|| err_string.contains("undeliverable")|| err_string.contains("user unknown")|| err_string.contains("user not found")- // The email account that you tried to reach is disabled. Learn more at https://support.google.com/mail/?p=DisabledUser|| err_string.contains("disabled"){- Ok(false)- } else {- Err(err)+ return Ok(Deliverability {+ has_full_inbox: false,+ is_deliverable: false,+ is_disabled: false,+ });}++ Err(err)}}}@@ -169,6 +212,7 @@ fn email_has_catch_all(smtp_client,&random_email.expect("Email is correctly constructed. qed."),)+ .map(|deliverability| deliverability.is_deliverable)}/// Get all email details we can.@@ -181,32 +225,15 @@ pub fn smtp_details() -> Result<SmtpDetails, LettreSmtpError> {let mut smtp_client = connect_to_host(from_email, host, port)?;- let has_catch_all = email_has_catch_all(&mut smtp_client, domain).unwrap_or(false);- let (deliverable, full_inbox) = match email_deliverable(&mut smtp_client, to_email) {- Ok(exists) => (exists, false),- Err(err) => {- let err_string = err.to_string();- // These messages mean that inbox is full, which also means that- // email exists- if err_string.contains("full")- || err_string.contains("insufficient")- || err_string.contains("over quota")- || err_string.contains("space")- {- (true, true)- } else {- debug!("Closing {}:{}, because of error '{}'.", host, port, err);- return Err(err);- }- }- };+ let is_catch_all = email_has_catch_all(&mut smtp_client, domain).unwrap_or(false);+ let deliverability = email_deliverable(&mut smtp_client, to_email)?;- // Quit.smtp_client.close();Ok(SmtpDetails {- deliverable,- full_inbox,- has_catch_all,+ has_full_inbox: deliverability.has_full_inbox,+ is_catch_all,+ is_deliverable: deliverability.is_deliverable,+ is_disabled: deliverability.is_disabled,})}diff --git a/serverless/Cargo.toml b/serverless/Cargo.tomlindex db7b8570..27971bb5 100644--- a/serverless/Cargo.toml+++ b/serverless/Cargo.toml@@ -1,6 +1,6 @@[package]name = "check_if_email_exists_serverless"-version = "0.3.2"+version = "0.4.0"authors = ["Amaury Martiny <[email protected]>"]description = "Check if an email address exists without sending any email"edition = "2018"diff --git a/src/cli.yml b/src/cli.ymlindex a357f8bb..73698f23 100644--- a/src/cli.yml+++ b/src/cli.yml@@ -1,5 +1,5 @@name: check_if_email_exists-version: '0.3.2'+version: '0.4.0'author: Amaury Martiny <[email protected]>about: Check if an email address exists without sending any email.args:diff --git a/src/main.rs b/src/main.rsindex 9d9082e8..e373de48 100644--- a/src/main.rs+++ b/src/main.rs@@ -20,9 +20,9 @@ extern crate serde;use check_if_email_exists_core::email_exists;use clap::App;-use serde_json::Result as JsonResult;+use serde_json;-fn main() -> JsonResult<()> {+fn main() -> serde_json::Result<()> {env_logger::init();// The YAML file is found relative to the current file, similar to how modules are founddiff --git a/test_suite/Cargo.toml b/test_suite/Cargo.tomlindex 4f8f4091..16e4e090 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.3.2"+version = "0.4.0"authors = ["Amaury Martiny <[email protected]>"]description = "Check if an email address exists without sending any email"edition = "2018"diff --git a/test_suite/src/lib.rs b/test_suite/src/lib.rsindex 79f25876..93e0b999 100644--- a/test_suite/src/lib.rs+++ b/test_suite/src/lib.rs@@ -35,13 +35,4 @@ mod tests {"{\"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\",\"username\":\"foo\",\"valid_format\":true}}");}-- #[test]- #[ignore]- fn should_output_error_when_blocked_by_isp() {- assert_eq!(- serde_json::to_string(&email_exists("[email protected]", "[email protected]")).unwrap(),- "{\"mx\":{\"records\":[\"in1-smtp.messagingengine.com.\",\"in2-smtp.messagingengine.com.\"]},\"smtp\":{\"error\":{\"type\":\"BlockedByIsp\"}},\"syntax\":{\"address\":\"[email protected]\",\"domain\":\"fastmail.com\",\"username\":\"someone\",\"valid_format\":true}}"- );- }}