lychee_lib/checker/
mail.rs

1#[cfg(all(feature = "email-check", feature = "native-tls"))]
2use http::StatusCode;
3
4#[cfg(all(feature = "email-check", feature = "native-tls"))]
5use crate::ErrorKind;
6
7use crate::{Status, Uri};
8
9#[cfg(all(feature = "email-check", feature = "native-tls"))]
10use check_if_email_exists::{CheckEmailInput, Reachable, check_email};
11
12#[cfg(all(feature = "email-check", feature = "native-tls"))]
13use crate::types::mail;
14
15/// A utility for checking the validity of email addresses.
16///
17/// `EmailChecker` is responsible for validating email addresses,
18/// optionally performing reachability checks when the appropriate
19/// features are enabled.
20#[derive(Debug, Clone)]
21pub(crate) struct MailChecker {}
22
23impl MailChecker {
24    /// Creates a new `EmailChecker`.
25    pub(crate) const fn new() -> Self {
26        Self {}
27    }
28
29    /// Check a mail address, or equivalently a `mailto` URI.
30    ///
31    /// URIs may contain query parameters (e.g. `contact@example.com?subject="Hello"`),
32    /// which are ignored by this check. They are not part of the mail address
33    /// and instead passed to a mail client.
34    #[cfg(all(feature = "email-check", feature = "native-tls"))]
35    pub(crate) async fn check_mail(&self, uri: &Uri) -> Status {
36        self.perform_email_check(uri).await
37    }
38
39    /// Ignore the mail check if the `email-check` and `native-tls` features are not enabled.
40    #[cfg(not(all(feature = "email-check", feature = "native-tls")))]
41    pub(crate) async fn check_mail(&self, _uri: &Uri) -> Status {
42        Status::Excluded
43    }
44
45    #[cfg(all(feature = "email-check", feature = "native-tls"))]
46    async fn perform_email_check(&self, uri: &Uri) -> Status {
47        let address = uri.url.path().to_string();
48        let input = CheckEmailInput::new(address);
49        let result = &(check_email(&input).await);
50
51        if let Reachable::Invalid = result.is_reachable {
52            ErrorKind::UnreachableEmailAddress(uri.clone(), mail::error_from_output(result)).into()
53        } else {
54            Status::Ok(StatusCode::OK)
55        }
56    }
57}