Skip to content

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

feat: Output JSON information with CLI (#53)

Amaury Martiny1d026d5d5df3
diff --git a/Cargo.lock b/Cargo.lock
index 88b80313..f7cb230b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -123,11 +123,15 @@ version = "0.2.3"
dependencies = [
"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)",
- "lettre 0.9.0 (git+https://github.com/lettre/lettre?rev=1cbcbbb11f7a39a5d5d3829ce4162ca1beafedfb)",
+ "futures 0.1.28 (registry+https://github.com/rust-lang/crates.io-index)",
+ "hyper 0.12.28 (registry+https://github.com/rust-lang/crates.io-index)",
+ "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)",
"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)",
+ "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",
"trust-dns-resolver 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -599,6 +603,23 @@ dependencies = [
"serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
+[[package]]
+name = "lettre"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bufstream 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "fast_chemail 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)",
+ "hostname 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
+ "native-tls 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "nom 4.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
[[package]]
name = "libc"
version = "0.2.58"
@@ -1735,6 +1756,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14"
"checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f"
"checksum lettre 0.9.0 (git+https://github.com/lettre/lettre?rev=1cbcbbb11f7a39a5d5d3829ce4162ca1beafedfb)" = "<none>"
+"checksum lettre 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c66afaa5dfadbb81d4e00fd1d1ab057c7cd4c799c5a44e0009386d553587e728"
"checksum libc 0.2.58 (registry+https://github.com/rust-lang/crates.io-index)" = "6281b86796ba5e4366000be6e9e18bf35580adf9e63fbe2294aadb587613a319"
"checksum linked-hash-map 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "ae91b68aebc4ddb91978b11a1b02ddd8602a05ec19002801c5666000e05e0f83"
"checksum lock_api 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c"
diff --git a/Cargo.toml b/Cargo.toml
index d5ac40b9..fe8df04f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -15,12 +15,16 @@ path = "src/cli/main.rs"
[dependencies]
clap = { version = "2.32", features = ["yaml"] }
env_logger = "0.6"
-lettre = { git = "https://github.com/lettre/lettre", rev = "1cbcbbb11f7a39a5d5d3829ce4162ca1beafedfb" }
+futures = "0.1"
+hyper = "0.12"
+lettre = "0.9"
log = "0.4"
native-tls = "^0.2"
rand = "0.7"
rayon = "1.2.0"
trust-dns-resolver = "0.12.0"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
[workspace]
members = [
diff --git a/ci/script.sh b/ci/script.sh
index 0985864e..1abf8441 100755
--- a/ci/script.sh
+++ b/ci/script.sh
@@ -17,8 +17,8 @@ main() {
# Run the binary with a $TEST_EMAIL, to test that the tool actually works.
# TODO This only works on osx now, see #11
if [ $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 "\"deliverable\": true"
+ cross run --target $TARGET --release $TEST_EMAIL | grep "\"deliverable\": true"
fi
}
diff --git a/src/cli/cli.yml b/src/cli/cli.yml
index 3cad9266..014664a6 100644
--- a/src/cli/cli.yml
+++ b/src/cli/cli.yml
@@ -4,10 +4,19 @@ author: Amaury Martiny <[email protected]>
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 (default: [email protected])'
+ help: The from email to use in the SMTP connection
takes_value: true
+ - HTTP:
+ long: http
+ help: Runs a HTTP server
+ - HTTP_PORT:
+ default_value: '3000'
+ long: http-port
+ help: Sets the port on which the HTTP server should bind. Only used when `--http` flag is on
+ takes_value: true
+ value_name: PORT
- TO_EMAIL:
help: The email to check
- required: true
index: 1
diff --git a/src/cli/http.rs b/src/cli/http.rs
new file mode 100644
index 00000000..ab8b3e50
--- /dev/null
+++ b/src/cli/http.rs
@@ -0,0 +1,93 @@
+// check_if_email_exists
+// Copyright (C) 2018-2019 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 futures::future;
+use futures::Stream;
+use hyper::rt::Future;
+use hyper::service::service_fn;
+use hyper::{Body, Request, Response, Server};
+use hyper::{Method, StatusCode};
+use serde::{Deserialize, Serialize};
+
+type BoxFut = Box<dyn Future<Item = Response<Body>, Error = hyper::Error> + Send>;
+
+/// JSON Request from POST /
+#[derive(Debug, Deserialize, Serialize)]
+pub struct PostReqBody {
+ from_email: String,
+ to_email: String,
+}
+
+/// Error Response from POST /
+#[derive(Debug, Deserialize, Serialize)]
+pub struct PostResError {
+ error: String,
+}
+fn req_handler(req: Request<Body>) -> BoxFut {
+ let mut response = Response::new(Body::empty());
+
+ match (req.method(), req.uri().path()) {
+ // Show instructions on GET /
+ (&Method::GET, "/") => {
+ *response.body_mut() =
+ Body::from("Send a POST request with JSON `{ \"from_email\": \"<email>\", to_email: \"<email>\" }` in the body");
+ }
+
+ // Do email_exists check on POST /
+ (&Method::POST, "/") => {
+ let checked = req.into_body().concat2().map(move |chunk| {
+ let body = &chunk.iter().cloned().collect::<Vec<u8>>();
+ let result = match serde_json::from_slice::<PostReqBody>(body) {
+ Ok(b) => {
+ println!("YEAH! {:?}", b);
+ // serde_json::to_string(&email_exists(&b.from_email, &b.to_email)).unwrap()
+ serde_json::to_string("todo").unwrap()
+ }
+
+ Err(err) => serde_json::to_string(&PostResError {
+ error: format!("{}", err),
+ })
+ .unwrap(),
+ };
+
+ *response.body_mut() = Body::from(result);
+ response
+ });
+
+ return Box::new(checked);
+ }
+
+ // 404 page on all other routes
+ _ => {
+ *response.status_mut() = StatusCode::NOT_FOUND;
+ }
+ };
+
+ Box::new(future::ok(response))
+}
+
+pub fn run(port: u16) -> () {
+ // This is our socket address...
+ let addr = ([127, 0, 0, 1], port).into();
+
+ let server = Server::bind(&addr)
+ .serve(|| service_fn(req_handler))
+ .map_err(|e| eprintln!("server error: {}", e));
+
+ // Run this server for... forever!
+ println!("Running server on localhost:{:?}", port);
+ hyper::rt::run(server);
+}
diff --git a/src/cli/main.rs b/src/cli/main.rs
index ae80e20b..b0b2c78d 100644
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -14,32 +14,42 @@
// 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/>.
-extern crate env_logger;
-#[macro_use]
extern crate clap;
+extern crate env_logger;
+extern crate futures;
extern crate lettre;
+mod http;
+
use check_if_email_exists::email_exists;
use clap::App;
-use std::process;
+use serde_json::Result as JsonResult;
-fn main() {
+fn main() -> JsonResult<()> {
env_logger::init();
// The YAML file is found relative to the current file, similar to how modules are found
- let yaml = load_yaml!("cli.yml");
+ let yaml = clap::load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
- let from_email = matches.value_of("FROM_EMAIL").unwrap_or("[email protected]");
+ let from_email = matches
+ .value_of("FROM_EMAIL")
+ .expect("FROM_EMAIL has a default value. qed.");
+ let http_port = matches
+ .value_of("HTTP_PORT")
+ .expect("HTTP_PORT has a default value. qed.");
+ let is_http = matches.is_present("HTTP");
let to_email = matches
.value_of("TO_EMAIL")
- .expect("'TO_EMAIL' is required. qed.");
-
- match email_exists(&from_email, &to_email) {
- Ok(exists) => println!("{:?}", exists),
- Err(err) => {
- println!("{:?}", err);
- process::exit(1);
- }
+ .expect("TO_EMAIL is required. qed.");
+
+ let output = serde_json::to_string_pretty(&email_exists(&to_email, &from_email))?;
+ println!("{}", output);
+
+ // Run the web server on :3000
+ if is_http {
+ http::run(http_port.parse::<u16>().unwrap());
}
+
+ Ok(())
}
diff --git a/src/lib.rs b/src/lib.rs
index 7a1a95c0..bbbafa3d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -20,135 +20,124 @@ extern crate log;
extern crate native_tls;
extern crate rand;
extern crate rayon;
+extern crate serde;
extern crate trust_dns_resolver;
-mod mx_hosts;
+mod mx;
mod smtp;
+mod syntax;
+mod util;
-use lettre::error::Error as LettreError;
-use lettre::smtp::SMTP_PORT;
-use lettre::EmailAddress;
-use mx_hosts::MxLookupError;
+use lettre::{smtp::SMTP_PORT, EmailAddress};
+use mx::{get_mx_lookup, MxDetails, MxError};
use rayon::prelude::*;
-use smtp::SmtpEmailDetails;
-use std::io::Error as IoError;
+use serde::{ser::SerializeMap, Serialize, Serializer};
+use smtp::{SmtpDetails, SmtpError};
use std::str::FromStr;
-use trust_dns_resolver::error::ResolveError;
+use syntax::{address_syntax, SyntaxDetails, SyntaxError};
-/// Errors that are returned by email_exists
+/// All details about email address, MX records and SMTP responses
#[derive(Debug)]
-pub enum EmailExistsError {
- /// ISP is blocking SMTP ports
- BlockedByIsp,
- /// To email address formatting error
- FromAddressError(LettreError),
- /// IO error
- Io(IoError),
- ///Error while resolving MX lookups
- MxLookup(ResolveError),
- /// To email address formatting error
- ToAddressError(LettreError),
+pub struct SingleEmail {
+ /// 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>,
}
-/// Information after parsing an email address
-#[derive(Debug)]
-pub struct AddressDetails {
- /// The email address as a lettre EmailAddress
- pub address: EmailAddress,
- /// The domain name, after "@"
- pub domain: String,
- /// The username, before "@"
- pub username: String,
- /// Is the email in a valid format?
- pub valid_format: bool,
-}
+// 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,
+ }
-/// All details about email address, MX records and SMTP responses
-#[derive(Debug)]
-pub struct EmailDetails {
- /// Details about the email address
- pub address: AddressDetails,
- /// Details about the MX records of the domain
- pub mx: Vec<String>,
- /// Details about the SMTP responses of the email
- pub smtp: SmtpEmailDetails,
+ let mut map = serializer.serialize_map(Some(1))?;
+ 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 fn email_exists(from_email: &str, to_email: &str) -> Result<EmailDetails, EmailExistsError> {
- debug!("Checking email '{}'", to_email);
-
- let from_email = match EmailAddress::from_str(from_email) {
- Ok(email) => email,
- Err(err) => return Err(EmailExistsError::FromAddressError(err)),
- };
- let to_email = match EmailAddress::from_str(to_email) {
- Ok(email) => email,
- Err(err) => return Err(EmailExistsError::ToAddressError(err)),
- };
-
- let iter: &str = to_email.as_ref();
- let mut iter = iter.split("@");
- let username = iter
- .next()
- .expect("We checked above that email is valid. qed.")
- .to_string();
- let domain = iter
- .next()
- .expect("We checked above that email is valid. qed.")
- .to_string();
+pub fn email_exists(to_email: &str, from_email: &str) -> SingleEmail {
+ let from_email = EmailAddress::from_str(from_email).unwrap_or(
+ EmailAddress::from_str("[email protected]").expect("This is a valid email. qed."),
+ );
- let address_details = AddressDetails {
- address: to_email,
- domain,
- username,
- valid_format: true,
+ debug!("Checking email '{}'", to_email);
+ let my_syntax = match address_syntax(to_email) {
+ Ok(s) => s,
+ e => {
+ return SingleEmail {
+ mx: Err(MxError::Skipped),
+ smtp: Err(SmtpError::Skipped),
+ syntax: e,
+ }
+ }
};
- debug!("Details of the email address: {:?}", address_details);
+ debug!("Details of the email address: {:?}", my_syntax);
debug!("Getting MX lookup...");
- let hosts = match mx_hosts::get_mx_lookup(address_details.domain.as_str()) {
- Ok(h) => h,
- Err(MxLookupError::Io(err)) => {
- return Err(EmailExistsError::Io(err));
- }
- Err(MxLookupError::ResolveError(err)) => {
- return Err(EmailExistsError::MxLookup(err));
+ let my_mx = match get_mx_lookup(&my_syntax.domain) {
+ Ok(m) => m,
+ e => {
+ return SingleEmail {
+ mx: e,
+ smtp: Err(SmtpError::Skipped),
+ syntax: Ok(my_syntax),
+ }
}
};
- let mut combinations = Vec::new(); // `(host, port)` combination
- for host in hosts.iter() {
- // We could add ports 465 and 587 too
- combinations.push((host.exchange(), SMTP_PORT));
- }
- let mx_details = combinations
+ debug!("Found the following MX hosts {:?}", my_mx);
+
+ // `(host, port)` combination
+ // We could add ports 465 and 587 too
+ let combinations = my_mx
+ .0
.iter()
- .map(|(host, _)| host.to_string())
- .collect::<Vec<String>>();
- debug!("Found the following MX hosts {:?}", mx_details);
+ .map(|host| (host.exchange(), SMTP_PORT))
+ .collect::<Vec<_>>();
- let smtp_details = combinations
+ let my_smtp = combinations
// Concurrently find any combination that returns true for email_exists
.par_iter()
// Attempt to make a SMTP call to host
.flat_map(|(host, port)| {
- smtp::email_details(
+ smtp::smtp_details(
&from_email,
- &address_details.address,
+ &my_syntax.address,
host,
*port,
- address_details.domain.as_str(),
+ my_syntax.domain.as_str(),
)
})
.find_any(|_| true)
// If all smtp calls timed out/got refused/errored, we assume that the
// ISP is blocking relevant ports
- .ok_or(EmailExistsError::BlockedByIsp)?;
+ .ok_or(SmtpError::BlockedByIsp);
- Ok(EmailDetails {
- address: address_details,
- mx: mx_details,
- smtp: smtp_details,
- })
+ SingleEmail {
+ mx: Ok(my_mx),
+ smtp: my_smtp,
+ syntax: Ok(my_syntax),
+ }
}
diff --git a/src/mx_hosts.rs b/src/mx.rs
similarity index 56%
rename from src/mx_hosts.rs
rename to src/mx.rs
index e414d9a4..0338aaed 100644
--- a/src/mx_hosts.rs
+++ b/src/mx.rs
@@ -14,23 +14,56 @@
// 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 std::io::Error as IoError;
+use crate::util::ser_with_display;
+use serde::{ser::SerializeMap, Serialize, Serializer};
+use std::io::Error;
use trust_dns_resolver::config::*;
use trust_dns_resolver::error::ResolveError;
use trust_dns_resolver::lookup::MxLookup;
use trust_dns_resolver::Resolver;
-pub enum MxLookupError {
- Io(IoError),
- ResolveError(ResolveError),
+/// Details about the MX lookup
+#[derive(Debug)]
+pub struct MxDetails(pub MxLookup);
+
+impl Serialize for MxDetails {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut map = serializer.serialize_map(Some(1))?;
+ map.serialize_entry(
+ "records",
+ &self
+ .0
+ .iter()
+ .map(|host| host.exchange().to_string())
+ .collect::<Vec<_>>(),
+ )?;
+ map.end()
+ }
+}
+
+/// Errors that can happen on MX lookups
+#[derive(Debug, Serialize)]
+pub enum MxError {
+ /// Skipped checking MX records
+ Skipped,
+ /// Error with IO
+ #[serde(serialize_with = "ser_with_display")]
+ Io(Error),
+ /// Error while resolving MX lookups
+ #[serde(serialize_with = "ser_with_display")]
+ Resolve(ResolveError),
}
-pub fn get_mx_lookup(domain: &str) -> Result<MxLookup, MxLookupError> {
+/// Make a MX lookup
+pub fn get_mx_lookup(domain: &str) -> Result<MxDetails, MxError> {
// Construct a new Resolver with default configuration options
let resolver = match Resolver::new(ResolverConfig::default(), ResolverOpts::default()) {
Ok(r) => r,
Err(err) => {
- return Err(MxLookupError::Io(err));
+ return Err(MxError::Io(err));
}
};
@@ -38,7 +71,7 @@ pub fn get_mx_lookup(domain: &str) -> Result<MxLookup, MxLookupError> {
// 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(l) => Ok(l),
- Err(err) => Err(MxLookupError::ResolveError(err)),
+ Ok(lookup) => Ok(MxDetails(lookup)),
+ Err(err) => Err(MxError::Resolve(err)),
}
}
diff --git a/src/smtp.rs b/src/smtp.rs
index c5637367..8688b7d2 100644
--- a/src/smtp.rs
+++ b/src/smtp.rs
@@ -14,17 +14,42 @@
// 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 lettre::smtp::client::net::NetworkStream;
use lettre::smtp::client::InnerClient;
use lettre::smtp::commands::*;
-use lettre::smtp::error::Error;
+use lettre::smtp::error::Error as LettreSmtpError;
use lettre::smtp::extension::ClientId;
use lettre::EmailAddress;
use rand::distributions::Alphanumeric;
use rand::Rng;
+use serde::Serialize;
use std::time::Duration;
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,
+ /// Does this domain have a catch-all email address?
+ pub has_catch_all: bool,
+}
+
+/// Error occured connecting to this email server via SMTP
+#[derive(Debug, Serialize)]
+pub enum SmtpError {
+ /// Skipped checking SMTP details
+ Skipped,
+ /// ISP is blocking SMTP ports
+ BlockedByIsp,
+ /// IO error when communicating with SMTP server
+ #[serde(serialize_with = "ser_with_display")]
+ Io(LettreSmtpError),
+}
+
/// Try to send an smtp command, close and return Err if fails.
macro_rules! try_smtp (
($res: expr, $client: ident, $host: expr, $port: expr) => ({
@@ -36,23 +61,12 @@ macro_rules! try_smtp (
})
);
-/// Details that we gathered from connecting to this email via SMTP
-#[derive(Debug)]
-pub struct SmtpEmailDetails {
- /// Can we send an email to this address?
- pub deliverable: bool,
- /// Is this email account's inbox full?
- pub full_inbox: bool,
- /// Does this domain have a catch-all email address?
- pub has_catch_all: bool,
-}
-
/// Attempt to connect to host via SMTP, and return SMTP client on success
fn connect_to_host(
from_email: &EmailAddress,
host: &Name,
port: u16,
-) -> Result<InnerClient<NetworkStream>, Error> {
+) -> Result<InnerClient<NetworkStream>, LettreSmtpError> {
debug!("Connecting to {}:{}", host, port);
let mut smtp_client: InnerClient<NetworkStream> = InnerClient::new();
let timeout = Some(Duration::new(3, 0)); // Set timeout to 3s
@@ -61,12 +75,12 @@ fn connect_to_host(
if let Err(err) = smtp_client.set_timeout(timeout) {
debug!("Closing {}:{}, because of error '{}'.", host, port, err);
smtp_client.close();
- return Err(Error::from(err));
+ return Err(LettreSmtpError::from(err));
}
// Connect to the host.
try_smtp!(
- smtp_client.connect(&(host.to_utf8().as_str(), port), timeout, None),
+ smtp_client.connect(&(host.to_utf8().as_str(), port), None),
smtp_client,
host,
port
@@ -97,7 +111,7 @@ fn connect_to_host(
fn email_deliverable(
smtp_client: &mut InnerClient<NetworkStream>,
to_email: &EmailAddress,
-) -> Result<bool, Error> {
+) -> Result<bool, LettreSmtpError> {
// "RCPT TO: [email protected]"
// FIXME Do not clone?
let to_email = to_email.clone();
@@ -108,10 +122,10 @@ fn email_deliverable(
// 250 2.1.5 Recipient e-mail address ok.
Ok(true)
} else {
- Err(Error::Client("Can't find 2.1.5 in RCPT command"))
+ Err(LettreSmtpError::Client("Can't find 2.1.5 in RCPT command"))
}
}
- None => Err(Error::Client("No response on RCPT command")),
+ None => Err(LettreSmtpError::Client("No response on RCPT command")),
},
Err(err) => {
let err_string = err.to_string();
@@ -140,7 +154,7 @@ fn email_deliverable(
fn email_has_catch_all(
smtp_client: &mut InnerClient<NetworkStream>,
domain: &str,
-) -> Result<bool, Error> {
+) -> Result<bool, LettreSmtpError> {
// Create a random 15-char alphanumerical string
let random_email = rand::thread_rng()
.sample_iter(&Alphanumeric)
@@ -155,13 +169,13 @@ fn email_has_catch_all(
}
/// Get all email details we can.
-pub fn email_details(
+pub fn smtp_details(
from_email: &EmailAddress,
to_email: &EmailAddress,
host: &Name,
port: u16,
domain: &str,
-) -> Result<SmtpEmailDetails, Error> {
+) -> 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);
@@ -187,7 +201,7 @@ pub fn email_details(
// Quit.
smtp_client.close();
- Ok(SmtpEmailDetails {
+ Ok(SmtpDetails {
deliverable,
full_inbox,
has_catch_all,
diff --git a/src/syntax.rs b/src/syntax.rs
new file mode 100644
index 00000000..7464eedd
--- /dev/null
+++ b/src/syntax.rs
@@ -0,0 +1,75 @@
+// check_if_email_exists
+// Copyright (C) 2018-2019 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 lettre::error::Error as LettreError;
+/// Information about the syntax of an email address
+use lettre::EmailAddress;
+use serde::{Serialize,Serializer};
+use std::str::FromStr;
+
+/// Syntax information after parsing an email address
+#[derive(Debug, Serialize)]
+pub struct SyntaxDetails {
+ /// The email address as a lettre EmailAddress
+ pub address: EmailAddress,
+ /// The domain name, after "@"
+ pub domain: String,
+ /// The username, before "@"
+ pub username: String,
+ /// Is the email in a valid format?
+ pub valid_format: bool,
+}
+
+#[derive(Debug)]
+pub struct SyntaxError(LettreError);
+
+impl Serialize for SyntaxError {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.collect_str(&self.0)
+ }
+}
+
+/// 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> {
+ let email_address = match EmailAddress::from_str(email_address) {
+ Ok(m) => m,
+ Err(error) => return Err(SyntaxError(error)),
+ };
+
+ let iter: &str = email_address.as_ref();
+ let mut iter = iter.split("@");
+ let username = iter
+ .next()
+ .expect("We checked above that email is valid. qed.")
+ .into();
+ let domain = iter
+ .next()
+ .expect("We checked above that email is valid. qed.")
+ .into();
+
+ let address_details = SyntaxDetails {
+ address: email_address,
+ domain,
+ username,
+ valid_format: true,
+ };
+
+ Ok(address_details)
+}
diff --git a/src/util/mod.rs b/src/util/mod.rs
new file mode 100644
index 00000000..1298518c
--- /dev/null
+++ b/src/util/mod.rs
@@ -0,0 +1,28 @@
+// check_if_email_exists
+// Copyright (C) 2018-2019 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)
+}